Testing for collisions

hi. I have a cube. and I have it so when I click on the cube it creates 4 new cubes around it. I don’t want it to create a new cube if there is already one in that position. so how can i test if there is a collision in front, back, left and right of the cube? notice that it should only test the exact point next to the cube. so for forward if the cube is on 1,1,1 it should only test the point at 1,1,2. also once the collision was detected i want do do some stuff, how do i get data out of the collision.

like
if(collision is detected){
do nothing
}else{
do something
}

Goat,

I think you’re probably going to want to use Physics.OverlapSphere. You could also do it with RayCasting or SphereCasting, but they’re more for checking what colliders lie along a line, where the overlap sphere is better for just checking a point. OverlapSphere returns a collider, which you can then use to get the gameObject and any children modules you might need to “do something” :wink:

Cheers!
Cahman

Hi Cahman

thanks for the reply :slight_smile:

so if i understand it correctly i can do this? :

void DoMethod(){
if(Physics.OverlapSphere(new Vector3(transform.position.x + 1, transform.position.y, transform.position.z), 0.1f).Equals(null)){
DoMore();
}
}

I’m probably doing something wrong, It seems it gets a collision even if there is nothing at the point

Hi Goat,

I think I know the problem: Physics.OverlapSphere returns an array. If there are no collisions, it returns an empty array, but an empty array is not equal to null… its still something, just empty! So You should check if the return is empty, not if the return is null

if(Physics.OverlapSphere(new Vector3(transform.position.x + 1, transform.position.y, transform.position.z), 0.1f).Length == 0){

You should also make sure the sphere isn’t colliding with the original objecting your clicking on. Pausing the game and dropping in an actual sphere object is a good way to visualize it.

Cheers!
Cahman