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);
}
}
範例影片:
不同物理碰撞觸發對照表
collision detection occurs and messages are sent upon collision
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | |||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | |||||
Static Trigger Collider | ||||||
Rigidbody Trigger Collider | ||||||
Kinematic Rigidbody Trigger Collider |
Trigger message are sent upon collision
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | Y | ||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | Y | Y | |||
Static Trigger Collider | Y | Y | Y | Y | ||
Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
Kinematic Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
References
- https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
- https://docs.unity3d.com/Manual/CollidersOverview.html