if (colliderBox.isTouching (col) && col.CompareTag("barrier")) {
score++;
this.GetComponent<Renderer> ().material.color = col.GetComponent<Renderer> ().material.color;
}
if (spriteBox.IsTouching(col) && col.CompareTag("barrier") ) {
Debug.Log (col);
Debug.Log (colliderBox);
SceneManager.LoadScene (mainMenu);
}
目前在我的代码中,我使用 onTriggerEnter 来检测与名为“barrier”的对象的碰撞,但我必须用 3D 对象替换 2d spriteBox 和 2d colliderBox,现在 isTouching 不是 3D 碰撞器的属性。我找不到简单的替代品。我可以用什么来代替它们?
没有用于 3D 碰撞的
isTouching
函数的等效版本,但您可以自行构建。当 OnTriggerEnter
时,将涉及的两个碰撞体存储在一个集合中。当调用 OnTriggerExit
时,检查涉及的两个碰撞器,如果已经退出集合,请将它们从集合中删除。这就是我在 this 帖子中使用 CollisionDetection
脚本所做的事情。
将
CollisionDetection
脚本附加到将要碰撞的对象。
要检查
Collider
是否正在接触另一个 Collider
,请更改:
if (colliderBox.isTouching (col) && col.CompareTag("barrier")) { }
至:
if (CollisionDetection.IsTouching (colliderBox.gameObject, col.gameObject) && col.CompareTag("barrier")) { }
您还可以为 CollisionDetection 类添加 ExtensionMethod:
public static class ExtensionMethod
{
public static bool IsTouching(this Collider collider, Collider otherCollider)
{
return CollisionDetection.IsTouching(collider.gameObject, otherCollider.gameObject);
}
public static bool IsTouching(this GameObject collider, GameObject otherCollider)
{
return CollisionDetection.IsTouching(collider, otherCollider);
}
}
现在,假设
if (colliderBox.isTouching (col) && col.CompareTag("barrier"))
是 colliderBox
或 Collider
的类型,您的 GameObject
代码应该无需更改即可工作。
在与 OnTriggerEnter 方法中的问题进行长期斗争后,我找到了另一种方法
collider1.bounds.Intersects(collider2.bounds)
尽管有一种特殊情况,此方法不起作用,但如果 collider2 是一个像盒子一样的空心网格碰撞器,并且 collider1 在其中,即使它们没有接触,它的交集也会返回 true ,所以我建议使用简单的碰撞器,例如盒子和球体碰撞器
可以使用外部脚本中的 3D 对象来执行此操作。
这可以使用联系事件来完成。
文档和示例:“https://docs.unity3d.com/2021.3/Documentation/ScriptReference/Physics.ContactModifyEvent.html”
将碰撞体的“.hasModifyingContacts”值设置为 true。
“Physics.ContactModifyEvent”,通过物理系统中的这个变量,您可以确定当进行“可修改接触”的碰撞体撞击另一个碰撞体时会发生什么。
通过这种方式,您可以检测某些碰撞体何时发生碰撞,类似于“Collider.isTouching”选项。