首页 > 解决方案 > 如何检查物体是否在球体的顶部或底部碰撞

问题描述

我有一个可以来自任何方向的碰撞对象,我想检查相对于球体中心的位置。

在此处输入图像描述

我的想法是创建一个与穿过球体中心的箭头方向相同的向量,然后检查箭头位置是在新向量上方还是下方,但我不知道如何实现这一点。

标签: c#unity3dcollision-detection

解决方案


一般来说,Vector没有位置。它只是空间中的一个方向和大小。位置基本上一个向量本身,它从世界原点 (0,0,0) 指向相应的位置。因此,如果您只有一个方向矢量,则它不包含有关位置的任何信息。

您需要更好地定义顶部和底部,但如果您只想检查全局空间Y,您可以通过比较它们的轴值来简单地检查碰撞接触点是高于还是低于球体中心。

像这样的东西

// Assuming this script is on the Sphere
private void OnCollisionEnter(Collision collision)
{
    // You could of course take all contact points into account and take an average etc
    // but to keep things simple just use only one for now
    var contact = collision.GetContact(0);
    var contactPoint = contact.point;
    var ownCenter = contact.thisCollider.bounds.center;

    if(contactPoint.y > ownCenter.y)
    {
        Debug.Log("Hit on top half");
    }
    else
    {
        Debug.Log("Hit on bottom half");
    }
}

如果您想检查局部空间(例如,因为您的球体像图形中一样旋转),您可以使用几乎相同的方法,但只需先将位置转换为局部空间

var contactPoint = transform.InverseTransformPoint(contact.point);

// In the case for a sphere this should most probably be equal to simply using 0,0,0
// In case of a "SphereCollider" you could also use that specific type and then use "sphereCollider.center" which already is in local space
// But to have it working generally keep using the center for now
var ownCenter = transform.InverseTransformPoint(contact.thisCollider.bounds.center);

推荐阅读