Skip to content

Instantly share code, notes, and snippets.

@david-alejandro-reyes-milian
Created October 3, 2022 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-alejandro-reyes-milian/00348799f49f2880af398e71c6cd217d to your computer and use it in GitHub Desktop.
Save david-alejandro-reyes-milian/00348799f49f2880af398e71c6cd217d to your computer and use it in GitHub Desktop.
Moves an object around a 2D platform by using waypoints position and rotation.
using UnityEngine;
namespace Enemies
{
public class MoveAroundPlatform : MonoBehaviour
{
[SerializeField] private float moveSpeed;
[SerializeField] private Transform[] wayPoints;
[SerializeField] public int index;
[SerializeField] private float rotSpeed;
private const float MinDistance = 0.05f;
private bool shouldTurn;
private void Update()
{
var nextPointPosition = wayPoints[index].position;
transform.position = Vector2.MoveTowards(transform.position, nextPointPosition, moveSpeed * Time.deltaTime);
if (shouldTurn) TurnRotation();
var distanceToNextPoint = Vector2.Distance(transform.position, nextPointPosition);
var nextPointIsCloseEnough = distanceToNextPoint <= MinDistance;
if (!nextPointIsCloseEnough) return;
index = (index + 1) % wayPoints.Length;
shouldTurn = true;
}
private void TurnRotation() =>
transform.rotation =
Quaternion.RotateTowards(transform.rotation, wayPoints[index].rotation, rotSpeed * Time.deltaTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment