I’ve been thinking about this for the past two days. Been searching on the net but can’t find anything.
I came up with a code using empty game objects to show the sides of the box, but I’m sure there’s a more optimal and good way to do this. It’s pretty basic stuff but can’t find anything on the subject. I’ve tried collision contact points, but there was a bug where if the top part had a collision, the LEFT or RIGHT side was also a collision.
Is there an efficient/clean way to discover which sides of a box collider had a collision, or am I better using raycasts? In my game, the player is using raycasts, having no problem detecting the side of the player which has a collision. But with a box collider it’s a bit more complex it seems.
Thank you for anyone considering helping me.
why not simply compare the positions of the two objects?
void OnCollisionEnter(Collision c)
{ // get the direction of the collision
Vector3 direction = transform.position - c.gameObject.transform.position;
// see if the obect is futher left/right or up down
if (Mathf.Abs (direction.x) > Mathf.Abs (direction.y)) {
if(direction.x>0){print("collision is to the right");}
else{print("collision is to the left");}
}else{
if(direction.y>0){print("collision is up");}
else{print("collision is down");}
}
}
If anyone finds this question, I was able to use raycasting for my problem. I posted a script and video here if you are curious.
Youtube Link - [ 1 ]
Script Link - [ 2 ]
Use this to look for direction of collision
If this is included in script of a object which collides with c then this will print which side of c did a hit , you can also look to see if it hit the corners by checking the direction’s values
void OnCollisionEnter(Collision c)
{
Vector2 direction = c.GetContact(0).normal;
If( direction.x == 1 ) print(“right”);
If( direction.x == -1 ) print(“left”);
If( direction.y == 1 ) print(“up”);
If( direction.y == -1 ) print(“down”);
}