Rotation is off by a slight bit and its really stupid

Does anyone know why this might be the case?

    if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            gameObject.transform.Rotate(0, transform.rotation.y + 90f,0);
        }

running those code, it works as expected, however, after just a single rotation, the math is off. check this out:
rotating the object once: 90.00001
the second time: -179.293

and so on, it gets more off with each rotation. Why is this? the object starts with all rotations at 0, and i specified 90, no more no less, so what gives?

Your “second time” result doesn’t make sense, but you should never expect floating point arithmetic to be exact like you should with integer arithmetic. Floating point types can represent a huge range of numbers, but all with limited precision. It is best to think of them more as a good approximation rather than an exact value.

For more detailed explanations see the various wiki pages on floating point arithmetic and how it really works.

90.00001 is fine, and there won’t be anything you can realistically do about such minor inaccuracy. That’s just the way floating point math works.

-179.293 is not fine, and that’s because what you’re doing is incorrect. You can’t use “transform.rotation” the way you’re using it. “transform.rotation” is not a Vector3; it’s a Quaternion. Taking the y component of it on its own is pretty meaningless.

I’d recommend using transform.RotateAround if you’re trying to rotate around an axis like this. Of, use your original code, but don’t include “transform.rotation.y +”. Rotate doesn’t set the rotation to the given amount; it rotates it by that amount, so rotating by your rotation doesn’t make a lot of sense.

2 Likes

i figured it was a problem with floating points, but i dont know what else to do. Im just trying to rotate the object by 90 degrees in either direction with the left and right arrow keys.

Then transform.RotateAround() is probably fine. However, realize that RotateBy will happen all in one single frame. It won’t rotate smoothly or animate the rotation. If you want something like that, you can probably just search for performing smooth rotations to find a lot of examples.

You just have slight mistake in your script then. All you need is this:

gameObject.transform.Rotate(0, 90f,0);
1 Like

thanks, that worked and helps a lot.