Reputation: 63
I've recently started working on my first 2D game in Unity, but I'm stuck with a collision detection problem. Is there any easy way of getting the collision detection for the sides? My object has a Rigidbody2D
and a BoxCollider2D
.
Upvotes: 2
Views: 2370
Reputation: 17651
Let's say your object is A and the thing that just hit your object is B.
Like James Hogle said, you should use compare displacement between B and A in A's own coordinate system. However, what happens if your object is rotated? You need transform.InverseTransformPoint. Then check the quadrant of the collider.
void OnCollisionEnter2D(Collision2D coll) {
Vector3 d = transform.InverseTransformPoint(coll.transform.position);
if (d.x > 0) {
// object is on the right
} else if (d.x < 0) {
// object is on the left
}
// and so on
}
However, there is still a problem: To be more precise, we should check against contact points of the collision. You should use the coll.contacts property.
Upvotes: 2
Reputation: 3040
The Unity OnCollisionEnter2D method gives you a reference to the collider which has come in contact with your gameObject. Therefore, you can compare the position of your gameObject with the position of the gameObject that has hit you. For example:
void OnCollisionEnter2D(Collision2D coll)
{
Vector3 collPosition = coll.transform.position;
if(collPosition.y > transform.position.y)
{
Debug.Log("The object that hit me is above me!");
}
else
{
Debug.Log("The object that hit me is below me!");
}
if (collPosition.x > transform.position.x)
{
Debug.Log ("The object that hit me is to my right!");
}
else
{
Debug.Log("The object that hit me is to my left!");
}
}
Upvotes: 2