Trying to check if 3 points in a 3D Space are collinear.

Hello,

I’m trying to check if 3 points in a 3D space are collinear. I chose to make 2 Vector3 AB and BC and check if the cross-product of the two equals Vector3.zero. However, it’s not working. When I have a point in the top plane in position A2, one in the middle plane in B2 and one in the bottom plane in A2, it considers as if the points were collinear. Here is my code:

        int score = 0;
        for (int i = 0; i < playerSlots.Count - 1; i++)
        {
            for (int j = i + 1; j < playerSlots.Count - 1; j++)
            {
                if (Vector3.Cross(playerSlots[j] - playerSlots[i], playerSlots[playerSlots.Count - 1] - playerSlots[j]) == Vector3.zero)
                {
                    score++;
                    Debug.Log("score");
                }
            }
        }

Where playerSlots.Count are all the points the player put on the game.

Can anyone help me? I can provide more information if needed. Also, if there is a better way to do this, please tell me.

Thanks!

Output the result of your cross vector in an “else” and see what you’re getting. (Note: output the X,Y,Z components separately, because Vector3.ToString() only outputs to 1 decimal place) If you’re getting wild numbers, there’s something wrong with your math. If you’re getting stuff like 0.00000001, that’s just float imprecision.

Using == on anything float-based is a bad idea, because due to float imprecision, it will frequently have tiny tiny nonzero values even if the math is theoretically correct. The answer is to check for a range of values instead. In this case, you could do that efficiently by testing something like result.sqrMagnitude < 0.00001 instead of result ==Vector3.zero.

2 Likes

Alternatively, Mathf.Approximately() will return true if two floats are nearly the same - in case you don’t feel like checking a range. It is specifically intended for dealing with the imprecision of comparing 2 floats for equality.