Vector2.up doesn't always equal (0.00, 1.00)?

I’m running into a weird issue when trying to determine where the player is hitting on a hitbox.

I am using this code to detect a collision and then determine if they hit the wall or the floor part of a block.

private void OnCollisionEnter2D(Collision2D collision)
    {
        //First, check if it is the ground or not.
        if(collision.gameObject.tag == "Ground")
        {
            Vector2 colVect = collision.contacts[0].normal;
            Debug.Log(colVect);
            //Now, check if it is the wall or the floor. So we check contacts.
            if (colVect == Vector2.up)
            {
                //We're on the floor! :smile:
                isGrounded = true;
                isJumping = false;
                Debug.Log("Floor!");
            }
            else if(colVect == Vector2.left || colVect == Vector2.right)
            {
                //We're hitting a wall!
                touchingWall = true;
                Debug.Log("Wall!");
            }
            else
            {
                Debug.Log("THINGS FUCKED!");
            }
        }
    }

My problem is, that sometimes apparently Vector2.up isn’t equal to 0.00, 1.00, even though it totally is?

Using my debug output, I get the following instances:
(0.00, 1.00)
THINGS FUCKED!
(0.00, 1.00)
Floor!
(0.00, 1.00)
Floor!
(0.00, 1.00)
THINGS FUCKED!

Where the (0.00, 1.00) is the Debug.Log(colVect) and the text is what part of the if/else it ends up in.

Any idea why this is happening? (0.00, 1.00) should always be equal to Vector2.up, but sometimes it doesn’t go into the if statement for some reason?

You’re asking for float equals which is tricky. Search for floating point imprecision for more information on the subject, it is a computer-wide thing, not Unity specific.
What’s more or less Unity specific (well, .NET) is that ToString (and by extension Debug.Log) will output a rounded floating point number for you.
https://docs.unity3d.com/ScriptReference/Vector2.ToString.html

Your incoming vector may contain more digits. Try logging the components out with a more precise formatter.

And it’s always a bad idea to rely on floating point number equality. Avoid this as much as possible.

You can make a utility method like so:

public static bool AreEqual(Vector2 a, Vector2 b) =>
    Mathf.Approximately(a.x, b.x) && Mathf.Approximately(a.y, b.y);

Hope it’s correct, didn’t test it.

You absolutely don’t need this.
https://docs.unity3d.com/ScriptReference/Vector2-operator_eq.html

1 Like