Same Side of a Line
Check whether two points are on the same side of an infinite line when viewed from above on Unity’s XZ plane.
View the Unity C# source on GitHubResult
The same calculation as a Unity C# helper.
using UnityEngine;
public static class SameSideOfLine
{
public enum Result { SameSide, OppositeSides, AOnLine, BOnLine, BothOnLine, InvalidLine }
public static Result Check(Vector3 start, Vector3 end, Vector3 a, Vector3 b)
{
Vector3 direction = end - start;
direction.y = 0f;
float length = direction.magnitude;
if (length == 0f) return Result.InvalidLine;
direction /= length;
int sideA = Side(direction, a - start);
int sideB = Side(direction, b - start);
if (sideA == 0 && sideB == 0) return Result.BothOnLine;
if (sideA == 0) return Result.AOnLine;
if (sideB == 0) return Result.BOnLine;
return sideA == sideB ? Result.SameSide : Result.OppositeSides;
}
private static int Side(Vector3 direction, Vector3 offset)
{
float left = direction.z * offset.x;
float right = direction.x * offset.z;
float crossY = left - right;
float tolerance = 1e-6f * Mathf.Max(Mathf.Abs(left), Mathf.Abs(right));
if (Mathf.Abs(crossY) <= tolerance) return 0;
return crossY > 0f ? 1 : -1;
}
}