当两个非触发碰撞体接触时会发生碰撞事件。
碰撞事件的用法示例包括:
碰撞事件的处理主要涉及以下 API 函数:
Collider.OnCollisionEnter:当两个碰撞体首次接触时,Unity 会在每个碰撞体上调用此函数。Collider.OnCollisionStay:当两个碰撞体接触时,Unity 会在每次物理更新时,对每个碰撞体调用一次此函数。Collider.OnCollisionExit:当两个碰撞体停止接触时,Unity 会在每个碰撞体上调用此函数。对于碰撞事件,所涉对象中至少有一个必须具有动态物理体(即禁用 Is Kinematic 的刚体或关节体)。如果碰撞中的两个__ GameObject__Unity 场景中的基础对象,可以表示角色、道具、风景、摄像机、路径点等。GameObject 的功能由所附的组件决定。更多信息
See in Glossary 均是运动物理体,则碰撞不会调用 OnCollision 函数。
以下示例为当 Unity 调用每个函数时会向控制台打印消息。
using UnityEngine;
using System.Collections;
public class DoorObject : MonoBehaviour
{
// “other” refers to the collider that is touching this collider
void OnCollisionEnter (Collider other)
{
Debug.Log ("A collider has made contact with the DoorObject Collider");
}
void OnCollisionStay (Collider other)
{
Debug.Log ("A collider is in contact with the DoorObject Collider");
}
void OnCollisionExit (Collider other)
{
Debug.Log ("A collider has ceased contact with the DoorObject Collider");
}
}
有关 OnCollision 事件的实际应用示例,请参阅 碰撞体事件示例脚本。