[英]Unity 2D Collision Detection
我最近开始在Unity中开发我的第一个2D游戏,但遇到了碰撞检测问题。 有没有简单的方法来获取侧面的碰撞检测? 我的对象具有Rigidbody2D
和BoxCollider2D
。
Unity OnCollisionEnter2D方法为您提供了与游戏对象接触的对撞机的参考。 因此,您可以将gameObject的位置与命中您的gameObject的位置进行比较。 例如:
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!");
}
}
假设您的对象是A,而刚击中您的对象的对象是B。
就像James Hogle所说的那样,您应该在A自己的坐标系中使用B和A之间的比较位移。 但是,如果旋转对象会怎样? 您需要transform.InverseTransformPoint 。 然后检查对撞机的象限。
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
}
但是,仍然存在一个问题:更准确地说,我们应该检查碰撞的接触点。 您应该使用coll.contacts属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.