Skip to content

[Unity] 如何觸發碰撞事件(collision 和 trigger)

Last Updated on 2021-10-29 by Clay

在使用 Unity 製作遊戲的過程中,我們難免會需要處理遊戲物件的一些碰撞。比方說『吃到道具』、『撞到牆壁』...... 等等不同的情況。這時候我們可以透過 OnCollisionEnter()OnTriggerEnter() 來處理碰撞、觸發事件。

以下紀錄如何撰寫碰撞、觸發程式,並紀錄不同物理型態的物件碰撞觸發表格。


碰撞(collision)與觸發(trigger)程式

由於我是製作 2D 遊戲,這裡都以 2D 碰撞觸發函式做範例。

碰撞:

private void OnCollisionEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Snake")
    {
        Destroy(gameObject);
    }
}



觸發:

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Snake")
    {
        Destroy(gameObject);
    }
}




範例影片:

https://clay-atlas.com/wp-content/uploads/2021/06/SnakeEating-GameScene-Android-Unity-2019.4.27f1-Personal_-_DX11_-2021-06-12-13-36-54.mp4

不同物理碰撞觸發對照表

collision detection occurs and messages are sent upon collision

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static ColliderY
Rigidbody ColliderYYY
Kinematic Rigidbody ColliderY
Static Trigger Collider
Rigidbody Trigger Collider
Kinematic Rigidbody Trigger Collider
參考自 Unity 官方手冊



Trigger message are sent upon collision

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static ColliderYY
Rigidbody ColliderYYY
Kinematic Rigidbody ColliderYYY
Static Trigger ColliderYYYY
Rigidbody Trigger ColliderYYYYYY
Kinematic Rigidbody Trigger ColliderYYYYYY
參考自 Unity 官方手冊

References


Read More

Tags:

Leave a Reply取消回覆

Exit mobile version