Version: Unity 6.0 (6000.0)
语言 : 中文
创建和配置触发碰撞体
碰撞检测

碰撞体事件脚本示例

以下示例展示了从碰撞函数调用事件的方法。它们分别使用了 OnCollisionEnterOnTriggerEnter,但这些概念适用于所有 OnCollisionOnTrigger 函数。

示例:不同游戏对象属性的不同事件

您可以通过配置脚本,以根据另一个碰撞体的关联游戏对象的属性(例如其名称或标签),来触发不同的事件。例如,当您希望允许某些碰撞体而非其他碰撞体来生成事件时,这将很有用。

以下示例为根据触碰此碰撞体的另一碰撞体是否带有“玩家”或“敌人”标签来打印不同的消息。

using UnityEngine;
using System.Collections;

public class DoorObject : Monobehaviour
{
    private void OnCollisionEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            Debug.Log ("The player character has touched the door.")
        }

        if (other.CompareTag("Enemy"))
        {
            Debug.Log ("An enemy character has touched the door!")
        }
    }
}

示例:每次物理更新都会发送事件消息

以下示例使用了触发碰撞体来生成悬停板。触发碰撞体被直接放置在悬浮板游戏对象的正上方,并且会对处于其触发范围内的任何游戏对象施加一个持续向上的力。

using UnityEngine;
using System.Collections;

public class HoverPad : MonoBehaviour
{
    // define a value for the upward force calculation
    public float hoverForce = 12f;

    // whenever another collider is in contact with this trigger collider…
    void OnTriggerStay (Collider other)
    {
        // …add an upward force to the Rigidbody of the other collider.
        other.rigidbody.AddForce(Vector3.up * hoverForce, ForceMode.Acceleration) 
    }
}
创建和配置触发碰撞体
碰撞检测