Grid Movement gets fked up after rotating camera

I’m coding a game where the player can move a selector throughout the battlefield that is made of several nodes in a 3D grid. The problem is that, when move through the grid it moves perfectly, but as soon as I rotate the camera and change the rotation of the object in increments of 90f, things get really fcked up for no apparent reason and I start getting these weird amounts (the original code is a bit more complex but I simplyfied it):

    void Update()
    {
    if (Input.GetKeyDown(KeyCode.W))
        {
            transform.position += Getnextpos(transform.forward * 2);
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            transform.position += Getnextpos(transform.forward * -2);
        }
        else if (Input.GetKeyDown(KeyCode.A))
        {
            transform.position += Getnextpos(transform.right * -2);
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            transform.position += Getnextpos(transform.right * 2);
        }
    }

    Vector3 Getnextpos(Vector3 moveDirection)
    {
        Debug.Log("recieving: " + moveDirection);
        Debug.Log("move x: " + moveDirection.x + ", y : " + moveDirection.y + ", z: " + moveDirection.z);
        return moveDirection;
    }

With the code above let’s say I press W and I get this from the Debug.log
recieving: (2.00, 0.00, 0.00)
move x: 2, y : 0, z: 0

Or if I press A:
recieving: (0.00, 0.00, -2.00)
move x: 0, y : 0, z: -2

But when I rotate the camera 90 degrees (and properly changing the object’s rotation) so that the movement is the same relative to the camera, and press W I get this:
recieving: (-2.00, 0.00, 0.00)
move x: -2, y : 0, z: -2.384186E-07

Or this when pressing A:
recieving: (0.00, 0.00, 2.00)
move x: -2.384186E-07, y : 0, z: 2

How can I fix this? This has really sucked up all my patience. TIA!

What you’re seeing is just notation for very, very small numbers. -2.384186E-07 is just -0.0000002384186.

Just comes down to floating point imprecision. It likely isn’t an issue.

I see! All I had to do was to round it down and now it works wonders. Thank you!

Also, language please. There’s really no need for a title like that.

Thanks.

Whenever I move by grid cells, I prefer to track the grid cells as integers, which avoids this imprecision.

Then for presentation of the movement, you smoothly move the object between cell centers, all the while tracking the position as int x; int y;

I have a demo in my proximity buttons project. Search for the DemoMoveGridCell and DemoMoveGridCell2 scenes. This is the main movement script:

proximity_buttons is presently hosted at these locations:

https://bitbucket.org/kurtdekker/proximity_buttons