Hello everyone ![]()
I’m trying to write a coroutine that will spin a game object around the specified axis for n rotations before landing at the final target rotation. The math is giving me a hard time, and I feel like I’m overcomplicating it. But I know next to nothing about quaternions, so I’m at a loss ![]()
This is what I have currently:
yield return StartCoroutine( transform.SpinTo( 170, 3, Vector3.forward, 1.5f ) );
// ...
static public IEnumerator SpinTo( this Transform transform, float target, int rotations, Vector3 axis, float duration ) {
float elapsed = 0;
Vector3 start = transform.localRotation.eulerAngles;
// Zero out the dimensions not being rotated
Vector3 scaledStart = Vector3.Scale( start, axis );
// Find shortest distance between starting angle and zero
float deltaZero = Quaternion.Angle( Quaternion.Euler( scaledStart ), Quaternion.identity );
// Feels like the axis parameter should dictate the direction... (Vector3.forward vs. Vector3.back)
float direction = Mathf.Sign( target );
target += ( 360f * rotations * direction );
Vector3 targetEulerAngles = ( target + ( deltaZero * direction ) ) * axis;
while( elapsed < duration ) {
elapsed = Mathf.MoveTowards( elapsed, duration, Time.deltaTime );
transform.localRotation = Quaternion.Euler( start + ( targetEulerAngles * ( elapsed / duration ) ) );
yield return 0;
}
transform.localRotation = Quaternion.Euler( start + targetEulerAngles );
}
What’s frustrating is that this code works for most cases (I think…). But if, say, the game object starts with a rotation of (0, 0, 270) and I call transform.SpinTo( -20, 1, Vector3.forward, 5.0f ), the game object ends up with a final rotation of 160 ![]()
There must be an easier way to go about this… Any hints? ![]()
Cheers! ![]()