Given volume dimensions and direction, how to determine if Vector3 is contained

I am looking to essentially determine if a Vector3 point is within a volume defined by the following:


  • Vector3 direction
  • float Height
  • float Width
  • float Length
  • Vector3 Center point of one end of the volume

Ideally I wouldn’t use any functions not available to a seperate thread, but I can make it work if I need to use Unity-specific API calls.

According to the fine gentlemen over at StackExchange, if you can get ahold of the p1, p2, p4, and p5 described in the sketch, you can do something to the effect of:

public bool Within (Vector3 p, Vector3 p1, Vector3 p2, Vector3 p4, Vector3 p5) {
	Vector3 x = p1 - p2, y = p1 - p4, z = p1 - p5;

	float px = Vector3.Dot (p, x), py = Vector3.Dot (p, y), pz = Vector3.Dot (p, z);

	return (Vector3.Dot (x, p1) < px && px < Vector3.Dot (x, p2)) &&
		   (Vector3.Dot (y, p1) < py && py < Vector3.Dot (y, p4)) &&
		   (Vector3.Dot (z, p1) < pz && pz < Vector3.Dot (z, p5));
}

Found an answer that worked for me. Unsure if it is the most performant, but works well enough for my purposes. Essentially, we figure out our perpendicular angle and then add/subtract vectors of the appropriate size where appropriate. Then we perform the calculation below and we get the proper setup. I’m sure this can be cleaned up as I feel I have some of the angles going backwards but otherwise seems fine.

Vector3 originPOS = transform.position;
Vector3 direction = (target.position - originPOS).normalized;
Vector3 acrossDirection = Vector3.Cross(direction, Vector3.up).normalized;
Vector3 center = originPOS + (direction * range * .5f);

Vector3 rangeVector = direction * range * .5f;
Vector3 acrossVector = acrossDirection * width * .5f;
Vector3 upVector = Vector3.down * height * .5f;
    Vector3[0] points = new Vector3[8];
points[0] = center + acrossVector + upVector - rangeVector;
points[1] = center + acrossVector + upVector + rangeVector;
points[2] = center - acrossVector + upVector + rangeVector;
points[3] = center - acrossVector + upVector - rangeVector;
points[4] = center + acrossVector - upVector - rangeVector;
points[5] = center + acrossVector - upVector + rangeVector;
points[6] = center - acrossVector - upVector + rangeVector;
points[7] = center - acrossVector - upVector - rangeVector;

if(Within(interferer.position, points[0], points[1], points[3], points[4]))
{
	Debug.Log("In the way");
}
else
{
	Debug.Log("Not in the way");
}