Created
February 11, 2021 21:59
-
-
Save chrisyarbrough/2c43d0afff15ccbd7d37ad5b48a1161d to your computer and use it in GitHub Desktop.
Given are two angles start and end within the range 0..360, now rotate a point around a circle from start to end taking either the clockwise or counter-clockwise direction.
This file contains hidden or 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 System.Collections; | |
using UnityEditor; | |
using UnityEngine; | |
public class CircleMath : MonoBehaviour | |
{ | |
public Vector3 position = Vector3.right; | |
public float angleStart = 20; | |
public float angleEnd = 270; | |
public float duration = 1f; | |
private bool animating; | |
private void OnValidate() | |
{ | |
angleStart = Mathf.Repeat(angleStart, 360f); | |
angleEnd = Mathf.Repeat(angleEnd, 360f); | |
} | |
//[EditorButton("Counter Clockwise", Scope.PlayMode, 1f)] | |
//[EditorButton("Clockwise", Scope.PlayMode, -1f)] | |
private void DoAnimation(float direction) | |
{ | |
float start = angleStart; | |
float end = angleEnd; | |
if (direction < 0f) | |
end = WrapAround(angleEnd); | |
else | |
start = WrapAround(angleStart); | |
StopAllCoroutines(); | |
StartCoroutine(TurnImpl(start, end)); | |
} | |
private static float WrapAround(float angle) | |
{ | |
return angle > 180f ? angle - 360f : angle; | |
} | |
private IEnumerator TurnImpl(float start, float end) | |
{ | |
animating = true; | |
for (float elapsed = 0; elapsed < duration; elapsed += Time.deltaTime) | |
{ | |
float t = elapsed / duration; | |
float angle = Mathf.Lerp(start, end, t); | |
position = PositionFromAngle(angle); | |
yield return null; | |
} | |
yield return null; | |
animating = false; | |
} | |
private static Vector3 PositionFromAngle(float angle) | |
{ | |
var x = Mathf.Cos(angle * Mathf.Deg2Rad); | |
var y = Mathf.Sin(angle * Mathf.Deg2Rad); | |
return new Vector3(x, y, 0f); | |
} | |
private void OnDrawGizmos() | |
{ | |
Gizmos.color = Color.white; | |
Gizmos.DrawWireSphere(transform.position, 1); | |
Gizmos.color = Color.green; | |
var pos = PositionFromAngle(angleStart); | |
Gizmos.DrawSphere(pos, 0.05f); | |
pos += Vector3.right * 0.1f; | |
Handles.Label(pos, "Start"); | |
Gizmos.color = Color.yellow; | |
pos = PositionFromAngle(angleEnd); | |
Gizmos.DrawSphere(pos, 0.05f); | |
pos += Vector3.right * 0.1f; | |
Handles.Label(pos, "End"); | |
if (animating) | |
{ | |
Gizmos.color = Color.red; | |
Gizmos.DrawSphere(position, 0.1f); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment