using UnityEngine; public enum CircularDirection { Clockwise, CounterClockwise } public class CircularMovement : MonoBehaviour { [SerializeField] private GameObject objectToMove; [SerializeField] private bool reverseHalfway = false; [SerializeField] CircularDirection circularDirection = CircularDirection.Clockwise; [SerializeField, Range(0f, 20f)] private float startPosition = 0; [SerializeField, Range(0f, 50f)] private float angularSpeed = 1; [SerializeField, Range(0f, 50f)] private float rotationRadius = 20; //Internal vars private float _angle = 0f; private float _posX, _posY = 0f; private bool _flipDirection = false; private Vector2 _objecToMovePosition; private Transform _transform; private void Awake() { _transform = transform; } private void Start() { if(startPosition > 0) { //Set a starting point on the radius _posX = _transform.position.x + Mathf.Cos(startPosition) * rotationRadius; _posY = _transform.position.y + Mathf.Sin(startPosition) * rotationRadius; //Set the starting angle _angle = startPosition; //Assign the position to the moving object _objecToMovePosition.Set(_posX, _posY); objectToMove.transform.position = _objecToMovePosition; } } void Update() { Move(); } private void Move() { //Check if the moving object should reverse course back to the starting point if (reverseHalfway) { if (Mathf.Abs(_angle) > 3.14) _flipDirection = true; else if (Mathf.Abs(_angle) <= 0.01f) _flipDirection = false; } //Check which direction to move if (circularDirection == CircularDirection.Clockwise) _angle = _flipDirection ? _angle + Time.deltaTime * angularSpeed : _angle - Time.deltaTime * angularSpeed; else _angle = _flipDirection ? _angle - Time.deltaTime * angularSpeed : _angle + Time.deltaTime * angularSpeed; //Calculate the angle of the x and y positions and include the rotation radius _posX = _transform.position.x + Mathf.Cos(_angle) * rotationRadius; _posY = _transform.position.y + Mathf.Sin(_angle) * rotationRadius; //Assign the movment to the object that needs to be moved _objecToMovePosition.Set(_posX, _posY); objectToMove.transform.position = _objecToMovePosition; } #if UNITY_EDITOR private void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, rotationRadius); Gizmos.color = Color.green; float _posX = transform.position.x + Mathf.Cos(_angle) * rotationRadius; float _posY = transform.position.y + Mathf.Sin(_angle) * rotationRadius; Gizmos.DrawCube(new Vector2(_posX, _posY), new Vector3(3, 3, 3)); } #endif }