- Home /
checking collisions before instantiating (not Physics.OverlapSphere)
I would like to check for a collision before an object is instantiated at the start of my game, for procedural level creation 'road' avoidance.
Currently I am using:
var oHit : RaycastHit;
var objectPosition = new Vector3(Random.Range(-1.0,1.0) * length, 0, Random.Range(-1.0,1.0) * width);
var checkResult = Physics.OverlapSphere(objectPosition, 10);
if (checkResult.Length == 0)
{place = Instantiate(object);
but it is not 'accurate' enough, and either avoids the objects entirely, or clips through them. the objects are complex and a simple sphere does not encompass them. I'd prefer a method that would use the mesh to determine collision.
I would like to use:
var checkResult = object.rigidbody.SweepTest(objectPosition, oHit, 10);
if (checkResult == false)
{place = Instantiate(object);
But it does not work in any way. it may be because I had to make the object a child in order to reset its transform values to zero for instantiation (like 'freeze transformations' in maya); thus it (the parent) has no collider?
for example:
objectParent(translate 0,0,0)
|-object (translate 3892,2873,972)
Answer by PedramAUS · May 29, 2012 at 03:37 AM
You can instantiate the object in an invisible layer and check for the collision if there is no collision change the layer on the fly and make it visible, otherwise destroy it.
You'd need to wait one or several fixed update though, for the collision to be detected.
Right now I'm kind of doing this, that's not the problem. It's the actual way you check the collision that I need.
I'm making another, first layer with the first set of larger objects on, (pretty much the mask of the level, where I don't want things to spawn)
Then the second layer of objects I have shown above, comes in. is SUPPOSED to spawn anywhere but where the first 'masking' layer is.
Then I delete the 'masking' layer's objects.
However using the Physics.OverlapSphere method, it's too inaccurate for the meshes and I end up with it either too far away, or intersecting the mask.
What other method do I use to DETECT the collisions?
Answer by BSDGuyShawn · Oct 08, 2014 at 01:03 AM
I realize this is an old one, but I use a prefab that is essentially an empty gameobject with a sphere collider and script attached. I instantiate this prefab at the location I want to check. The script has uses Physics.OverlapSphere() in the void Awak() function. It seems to work ok.