# C# Looking for help with rotating sprites

## Recommended Posts

I am trying to rotate my car sprite just slightly to the left or right depending on input up to a small maximum. When I use this code, the rotation doesn't stop at the maximum i give it. When i try to reset the rotation back to its original state when not pressing any input, the car also jitters between a z axis rotation of 0 and 2.5. I don't understand why the rotation doesn't stop at the given maximums, nor do I understand why its jittering. Can anybody provide me some insight?

float movementHorizontal = 0f;
float movementVertical = 0f;

if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D))
{
}
else if (Input.GetKey(KeyCode.A))
{
movementHorizontal = -1;

if (transform.rotation.z < 10f)
{
transform.Rotate(zAxis, 2.5f);
}
}
else if (Input.GetKey(KeyCode.D))
{
movementHorizontal = 1;

if (transform.rotation.z > -10f)
{
transform.Rotate(zAxis, -2.5f);
}

}
else
{
if(transform.rotation.z > 0)
{
transform.Rotate(zAxis, -2.5f);
//transform.rotation.Set(0, 0, 0, 0);
}
else if (transform.rotation.z < 0)
{
transform.Rotate(zAxis, 2.5f);
//transform.rotation.Set(0, 0, 0, 0);
}

}

##### Share on other sites

Floating point numbers have a finite precision. In your last else branch you check for less than 0 and greater than 0, and doing nothing if equal to zero. However, the probability that the value is exactly 0 after some computation like rotation is very low; it is much more likely that values like 0.0000000123 will result. This is often the reason for stability problems like you observe.

One approach to overcome that problem is to weaken the comparison by considering a small tolerance value, i.e. check not for equal to 0 but very close to 0, like so:

if(transform.rotation.z > 0.01)
...
else if(transform.rotation.z < -0.01)
...
else
...

Finding an appropriate tolerance is a problem though, because it depends on the circumstances. In your case we're speaking of an orientation angle in degrees (presumably), so 0.01 is probably already a small enough value.

Another thing is that restricting values (to a maximum in your case) is sometimes better be done on the result, i.e. after the computation. This is a way to avoid overshooting.

##### Share on other sites

Wow, thanks to you both! I looked closer and my rotation was indeed not quite 0. The Mathf.Approximately was unknown to me. Thanks for pointing it out, I will give it a try. If it doesn't work out, I will try a manual check. Thanks again, fellas!

##### Share on other sites

Nice , it is very good topic , but there are very few comments

## Create an account

Register a new account

1. 1
Rutin
27
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633311
• Total Posts
3011312
• ### Who's Online (See full list)

There are no registered users currently online

×