[SOLVED] GameObject is moving very slightly when it shouldn't be

I have this piece of code running in my Update function:

    void Movement()
    {
        pos = Camera.main.WorldToViewportPoint(transform.position);
        pos.x = Mathf.Clamp(pos.x, 0.05f,0.99f);
        pos.y = Mathf.Clamp(pos.y, 0.05f,0.99f);
        transform.position = Camera.main.ViewportToWorldPoint(pos);

        transform.position += new Vector3(Input.GetAxisRaw("Horizontal"),
                                           Input.GetAxisRaw("Vertical"),
                                           0)*Time.deltaTime*travelSpeed;
    }

I notice that when I apply ViewportToWorldPoint my gameobject is very slightly moving in it’s x and y position and I can’t think of a way of stopping it.

Any help would be appreciated, thanks.

I’d output the exact values of pos.x and pos.y after line 5, then transform.position.x and transform.position.y after line 6, and the same after you apply your input. Doing so will tell you where the slight movement is coming from.

1 Like

I know where it’s coming from it’s just stopping it.

pos = Camera.main.WorldToViewportPoint(transform.position);
transform.position = Camera.main.ViewportToWorldPoint(pos);

If all the other code is commented out these are the two lines that make it move. I either need to put a buffer in or find another way of positioning the gameobject I guess.

EDIT: The gameobject stops moving when the camera is in orthographic. At least that gives me something to go off now…

If it is those two lines, I’d suspect you’re encountering an effect of limited floating point accuracy during these conversions.

For example, if you took the number 0.1234567 then multiplied it by 0.0001, then took the result and divided it by 0.0001, in the real math world you’d end up with the 0.1234567 you started with. But if you do that in C# using the float type for all of these numbers, you will end up with a number somewhere around 0.1235f. That is because the answer for 0.1234567 * 0.0001 cannot be accurately represented by the float type, but instead will be rounded to around 7 decimal places.

1 Like

Yeah, you generally shouldn’t rely on any math involving floating-point numbers to give you an exact result.

2 Likes

…well this works. Maybe theres a better way like always :smile:

Vector3 tmpPos = transform.position;
        transform.position = new Vector3(Mathf.Round(tmpPos.x),Mathf.Round(tmpPos.y),Mathf.Round(tmpPos.z));
1 Like