Skip to content

Instantly share code, notes, and snippets.

@JonathanTurnock
Created May 16, 2020 16:57
Show Gist options
  • Save JonathanTurnock/5d6f2885d75839bd54ea6388b70e35d2 to your computer and use it in GitHub Desktop.
Save JonathanTurnock/5d6f2885d75839bd54ea6388b70e35d2 to your computer and use it in GitHub Desktop.
Simple Vector2 Movement BaseClass
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] public float speed = 1f;
private List<Transform> waypoints = new List<Transform>();
private int currentWaypointIdx = 1;
protected void Update()
{
transform.position = Vector2.MoveTowards(transform.position, GetCurrentWaypoint().position, GetFpsAdjustedSpeed());
}
// Public API
/**
* Adds a new Waypoint to the Objects list of Waypoints
*/
public void AddWaypoint(Transform waypoint)
{
waypoints.Add(waypoint);
}
/**
* Gets the number of waypoints the Object has
*/
public int NumberOfWaypoints()
{
return waypoints.Count;
}
/**
* Sets the Given Waypoint Index to be the targeted waypoint of the object
*
* (Indexes start at 1)
*/
public void SetWaypoint(int waypointIndex)
{
currentWaypointIdx = waypointIndex;
}
/**
* Checks if the route has been completed by inspecting the current position relative to the final waypoint.
*
* Returns True if the current position is the position of the final waypoint
*/
public bool IsRouteComplete()
{
Transform lastWaypoint = waypoints[NumberOfWaypoints() - 1];
return transform.position.x == lastWaypoint.position.x && transform.position.y == lastWaypoint.position.y;
}
// Subclass API
/**
* Gets the Current Waypoint the Object is Targeting
*/
protected Transform GetCurrentWaypoint()
{
return waypoints[currentWaypointIdx - 1];
}
// Private API
/**
* Gets the Framerate Adjusted Speed for calculating movement
*/
private float GetFpsAdjustedSpeed()
{
return speed * Time.deltaTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment