- Home /
How to check if a point is in a rotated BoxCollider?
I've got pathing code that involves checking if an enemy is in an area that it isn't supposed to be. These areas are defined by boxes with IsTrigger colliders, and these boxes are often rotated to match with the desired areas. The current code is this:
private bool IsInExclusionZone(out int index)
{
for (int i = 0; i < regionTracker.exclusionZones.Length; i++)
{
// PROBLEM: Bounds are in a worldspace box
// Listing BoxCollider instead changes nothing
if (regionTracker.exclusionZones[i].GetComponent<Collider>().bounds.Contains(transform.position))
{
index = i;
return true;
}
}
index = -1;
return false;
}
The problem is, if one of the exclusion zones is say, rotated 45 degrees on the y axis, a point that is outside the collider, but still within the worldspace bounds of the collider, will register as being "contained". How do I alter this code so that it only returns true when transform.position is inside the actual collider?
Answer by Glurth · Jan 17, 2017 at 12:26 AM
The Bounds returned by a Collider is in world-space coordinates, and is axis aligned. So, if you rotate the collider, the bound's various edge-size may change, but it will remain axis aligned.
So if you want to see if a point is contained within rotated collider (not it's bounds), I would recommend using the collider's raycast function. Set the origin as the world-space point you want to test, and the second point as the world-space center of the bounds. If no collision is detected you are inside. (works consistently for convex colliders only.)
e.g.
Vector3 posToCheck = positiontoCheck.position;
Vector3 offset = colliderToCheck.bounds.center- positiontoCheck.position;
Ray inputRay = new Ray(posToCheck,offset.normalized);
RaycastHit rHit;
Debug.DrawRay(posToCheck, offset);
if (!colliderToCheck.Raycast(inputRay, out rHit, offset.magnitude * 1.1f))
inside = true;
else
inside = false;
Answer by mkgame · Dec 28, 2018 at 11:26 AM
Sometimes we just don't want to have a collider, because we have limited layers. I would recommend to set a bound in editor mode or calculate the bounds in Awake from all Renderers (except the ParticleSystem and LineRenderer). Then rotate the point back, which should be checked, by the rotation of your GameObject. The pivot point for rotation must be the GameObject pivot point. Then check this point by bounds.Contains(...).
Your answer
Follow this Question
Related Questions
Get closest point on collider on at a certain z depth 0 Answers
Unity Height Glitch (explained) 1 Answer
How Does OnTriggerEnter() Work? 0 Answers
How would i find the center of an object with a Y axis offset to find the center on the top face? 1 Answer
Bounds.Contains not working properly 3 Answers