September 20, 2012

Collinearity in Unity3D

Tags: Technical, Unity

In Unity3D how can it be determined if a point is on the line segment joining two other points? My current project throws up just such geometry problems regularly. The problem as expressed above is a question of collinearity, that is whether some points form a line. The first step uses the cross product. If you have the points A, B, C then if the cross product of the line AB and the line AC is 0, AB and AC must be parallel. Furthermore, since both lines include the point A, all the points must in fact be collinear. Luckily, there is a cross product function built into the Unity3D library, Vector3.Cross.

Next, just because A, B, C are collinear does not mean C is in between A and B. To determine this, check that C is inside the 3D volume with A & B as diametrically opposed corners. That is just check that C’s x-axis value is inbetween A’s & C’s and the same for its y-axis and z-axis values. The function below combines these tests. Note the range checks are performed first. This is because I imagine that the cross product is more computationally expensive (but I have no evidence for this) so should occur only if the faster calls succeed.

public static bool OnLine(Vector3 start, Vector3 end, Vector3 inBetween) {
  return inBetween.x <= end.x && inBetween.x >= start.x
    && inBetween.y <= end.y && inBetween.y >= start.y
    && inBetween.z <= end.z && inBetween.z >= start.z
    && Vector3.Cross(end - start, inBetween - start) ==;