Version: Unity 6.0 (6000.0)
语言 : 中文
不同类型碰撞体之间的交互
触发事件(OnTrigger)

碰撞事件 (OnCollision)

当两个非触发碰撞体接触时会发生碰撞事件。

碰撞事件的用法示例包括:

  • 当射弹击中目标时,同时摧毁射弹和敌人。
  • 当玩家角色触碰到一扇门时,触发一个动画来打开这扇门。
  • 当玩家角色触碰到一个增强道具时,增大玩家角色的体型。

碰撞事件的处理主要涉及以下 API 函数:

对于碰撞事件,所涉对象中至少有一个必须具有动态物理体(即禁用 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 事件的实际应用示例,请参阅 碰撞体事件示例脚本

不同类型碰撞体之间的交互
触发事件(OnTrigger)