Question by
agiro · Sep 09, 2016 at 01:55 PM ·
c#unity 5quaternion
Quaternion lerp back and forth
I want to lerp along the Z axis forth and back the same amount to avoid spinning (as my sprite is not a circular one). To do this I planned to random a forward angle, store it, lerp to it then lerp back with the same amount. However, this gives some weird popping as when the backwards rotations starts the starting angle wouldn't be the same, but it is. When I call it, I give it the same time to interpolate between. Some code:
IEnumerator LerpQuat(QuatLerpInput rotThis, float time, float leftBoundary, float rightBoundary)
{
/*
* we want to rotate forward, then backward the same amount
* to avoid spinning. we store the given value to both of these.
*/
Transform stuffToRot = rotThis.godRayGO.transform;
float lastTime = Time.realtimeSinceStartup;
float timer = 0.0f;
switch (rotThis.rotState)
{
case (QuatLerpInput.RotationStates.rotAway):
rotThis.deltaRot = Random.Range(leftBoundary, rightBoundary);
while (timer < time)
{
stuffToRot.rotation = Quaternion.Euler(stuffToRot.rotation.x, stuffToRot.rotation.y,
Mathf.LerpAngle(rotThis.idleRot, rotThis.idleRot + rotThis.deltaRot, timer / time));
timer += (Time.realtimeSinceStartup - lastTime);
lastTime = Time.realtimeSinceStartup;
yield return null;
}
rotThis.rotState = QuatLerpInput.RotationStates.setBack;
break;
case (QuatLerpInput.RotationStates.setBack):
while (timer < time)
{
stuffToRot.rotation = Quaternion.Euler(stuffToRot.rotation.x, stuffToRot.rotation.y,
Mathf.LerpAngle(rotThis.idleRot + rotThis.deltaRot, rotThis.idleRot, timer / time));
timer += (Time.realtimeSinceStartup - lastTime);
lastTime = Time.realtimeSinceStartup;
yield return null;
}
rotThis.rotState = QuatLerpInput.RotationStates.rotAway;
break;
}
}
public class QuatLerpInput
{
public GameObject godRayGO;
public float deltaRot;
public float idleRot;
public enum RotationStates
{
rotAway, setBack
}
public RotationStates rotState = RotationStates.rotAway;
public QuatLerpInput(GameObject godRayGO)
{
this.godRayGO = godRayGO;
deltaRot = godRayGO.transform.rotation.z;
idleRot = godRayGO.transform.rotation.z;
}
}
Comment
Your answer
Follow this Question
Related Questions
Flip 3D Character Rotation 180 on Y axis 1 Answer
C# I need to move object in a cycle 0 Answers
Keys "A" and "D" to TURN and not TURN and RUN 0 Answers
Can someone please help me with mesh extrusion 0 Answers
NullReferenceException: Object reference not set to an instance of an object, again 2 Answers