Created
October 3, 2022 21:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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