Hey everyone, I’ve only just started using Unity and I like it so far, but I’ve run into a problem that is probably caused by unreliable floats and bad code^^
I have a cube transform that I want to rotate smoothly by 90 degree, so it should start at (0,0,0) and end at (0,90,0). After searching the web and trying various methods, I found that Quaternion.Lerp seemed to be the “best” one.
Unfortunately though in my implementation it ends the rotation at (0, 90.00001, 0)…
Also: while trying to remove irrelevant code(for easy reading), I found that if I rotate the cube just around the x axis, it works more reliable(which made me think I found the source of the problem -.-)… In my implementation it’s not really working though…
Here’s the code for you to look at:
using UnityEngine;
using System.Collections;
public class rotateCube : MonoBehaviour
{
void Update()
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 90, 0), Time.time *0.1f);
}
}
The script is attached to a cube at pos and rotation (0,0,0).
Any help for solving this problem or giving me a (preferably simple) alternative would be highly appreciated^^
The issue is called “floating point accuracy” and comes from the way in which fractions are held by computers. There isn’t a “fix” for that. You will need to accommodate it.
Why is 0.00001 of a degree an issue in what you are trying to do?
1 Like
The 0.00001 variation is only occurring with the “cleaned” code. In my actual code it results in more variation and the main problem would be, that it’s only getting worse, the more you rotate it.
Another problem is, that sometimes the other 2 axes (that should not change at all) both rotate by 180 degree -.-
Is it really that hard to have an object just rotate by 90 degree, without anything else happening? I would gladly use a different method, if it’s reliable…
I cant currently test this, but i think it should be more accurate, you could also only take the axis you need to avoid the 180 rotation issue.
Quaternion startRot;
Float rotProg;
Void Awake(){
startRot = transform.rotation;
rotProg = 0.0f;
}
Void Update(){
If(rotProg < 1){
rotProg += Time.deltaTime* 0.1f;
}
transform.rotation = [URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Quaternion']Quaternion[/URL].[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Lerp']Ler[/URL]p(startRot, [URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Quaternion']Quaternion[/URL].[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Euler']Euler[/URL](0, 90, 0), rotProg);
}