- Home /
Smooth transition from 360 to 0 degrees
Hello, I have a wheel which rotates by 45 degree on Button press. My problem is that if I am on 315 degree It instead of rotating +45 degree to 360 it rotates -315 degree back to 0. How can I fix this or make 360 equal to 0? Any help is appreciated.
Greetings from Switzerland.
snow2405
if (rotating) //This is in Update
{
Vector3 to = new Vector3(0, 0, AngleofEveryColor[Cubecolor]); // Array with 45 degree steps
if (Vector3.Distance(ColorCirle.eulerAngles, to) > 0.5f) // stops lerping if distance is less than 0.5 degree
{
ColorCirle.eulerAngles = Vector3.Lerp(ColorCirle.rotation.eulerAngles, to, Time.deltaTime*10.0f);
}
else
{
ColorCirle.eulerAngles = to;
//rotating = false; // deactivated for testing
}
}
Answer by yummy81 · Mar 03, 2018 at 01:44 PM
I would use Quaternions. Euler angles are responsible for this weird behaviour. Try my code. You can adjust the angle and axis of rotation in this line:
Quaternion target = transform.rotation * Quaternion.AngleAxis(-45f, Vector3.forward);
Here's my code:
private bool rotating;
private void Update()
{
if (Input.GetMouseButtonDown(0) && !rotating)
{
StartCoroutine(RotateMe(1f));
}
}
private IEnumerator RotateMe(float duration)
{
rotating = true;
float t = 0f;
Quaternion target = transform.rotation * Quaternion.AngleAxis(-45f, Vector3.forward);
while (t < 1f)
{
t += Time.deltaTime / duration;
transform.rotation = Quaternion.Lerp(transform.rotation, target, t);
yield return null;
}
rotating = false;
}
Thank you, works perfect! I used Quaternions before but I guess I made some mistakes because after a few turns they always would be off by 2-3 degrees
Some drift will happen if you keep applying operations to the same floating point units (like what a quaternion would have internally), however I'm surprised it's off by 2-3 degrees. This is probably happening because the lerp hasn't "completed", due to the nature of lerp, which really never gets to it's target. It just keeps getting closer, and closer, and closer. So after the 1st rotation, when you hit the mouse button the 2nd time, the angle is probably only at 44.995 or something. The faster you click, the worse it will be.
What I would do is keep an integer value that goes between 0 and 7 (you increment it when the user hits the mouse button). Then you choose your lerp target from that integer: Quaternion target = Quaternion.AngleAxis(-45f * myInt, Vector3.forward);
Your answer
Follow this Question
Related Questions
Joystick movement for 3d mobile player 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Rotating object around Z axis with lerp/slerp 1 Answer
Can't destroy an ui element 2 Answers