判断一个点是否在三角形内部,思路是:假设点P位于三角形内,沿着ABCA的方向在三条边上行走时,点P始终位于边AB,BC和CA的同侧。
代码实现:
public Transform A, B, C, P;
public void OnDrawGizmos()
{
Gizmos.DrawLine(A.position, B.position);
Gizmos.DrawLine(B.position, C.position);
Gizmos.DrawLine(C.position, A.position);
}
public bool IsInboundsTriangle(Vector3 A,Vector3 B,Vector3 C,Vector3 P)
{
if (IsSameSide(A, B, C, P) && IsSameSide(B, C, A, P) && IsSameSide(C, A, B, P))
return true;
return false;
}
private bool IsSameSide(Vector3 A, Vector3 B, Vector3 C, Vector3 P)
{
Vector3 PA = P - A;
Vector3 AB = A - B;
Vector3 CA = C - A;
Vector3 PAB = Vector3.Cross(PA, AB);
Vector3 CAB = Vector3.Cross(CA, AB);
if (Vector3.Dot(PAB, CAB) >= 0)
return true;
return false;
}