- Home /
Question by
Buretto · Dec 04, 2017 at 01:14 AM ·
instantiatemeshobjectmeshrendereroverlap
How to detect if object is within another object?
I am instantiating objects above my scene and then raycasting them down into position on the ground, and I have attempted to make a script which would remove any objects that are overlapping. It does not seem to work because sometimes the objects will still overlap. Here is my code:
`public class spawnChecker : MonoBehaviour {
// Use this for initialization
void Start () {
obstacleSpawner obstacleSpawner = gameObject.GetComponentInParent<obstacleSpawner> ();
RaycastHit hit;
Vector3 down = new Vector3 (0, -1, 0);
transform.rotation = Quaternion.Euler (14, 0, 0);
if (Physics.Raycast (transform.position, down, out hit, Mathf.Infinity)) {
if (hit.transform.tag == "Ground") {
Vector3 newLocation = hit.point;
newLocation += new Vector3 (0, transform.localScale.y / 2, 0);
transform.position = newLocation;
CheckBounds ();
if (CheckBounds() == false) {
obstacleSpawner.spawn (1);
Destroy (gameObject);
}
} else {
obstacleSpawner.spawn (1);
Destroy (gameObject);
}
} else {
obstacleSpawner.spawn (1);
Destroy (gameObject);
}
}
public bool CheckBounds()
{
Bounds objectBounds = (gameObject.GetComponent<MeshFilter>().mesh.bounds);
float sqrHalfObjectSize = objectBounds.extents.sqrMagnitude;
//float overlapingSphereRadius = Mathf.Sqrt (sqrHalfObjectSize + sqrHalfObjectSize);
Collider[] hitColliders = Physics.OverlapBox(transform.position,objectBounds.extents,transform.rotation,1 << 8);
foreach(Collider otherCollider in hitColliders)
{
if (otherCollider.bounds.Intersects (objectBounds))
return (false);
}
return (true);
}
}
`
Would I be better off using OnCollission methods? P.S., I have checked the bounding boxes for the mesh's and they are all in order, so what is going wrong?
Comment