public class CollisionDetection : MonoBehaviour
{
public Color color1 = Color.red;
public Color color2 = Color.white;
private GameObject ignoreCollisionWith
void OnCollisionEnter(Collision col)
{
if(col.gameObject == ignoreCollisionWith) return;
if(col.gameObject.TryGetComponent<CollisionDetection>(out var other))
{
// Set the color for both involved objects
GetComponent<Renderer>(). material.color = color1;
other.GetComponent<Renderer>(). material.color = color2;
// Tell the other object to do nothing for this collision with you
other.ignoreCollisionWith = gameObject;
}
}
void FixedUpdate()
{
ignoreCollisionWith = null;
}
}
這聽起來像是你在問“如何只處理其中一方的碰撞?”
碰撞發生在物理更新例程中,因此基本上在
FixedUpdate
之后。請參閱事件消息的執行順序,您可以看到
FixedUpdate
總是在處理所有OnCollisionXY
之前執行。因此,您可以在第一個
OnCollisionEnter
中存儲對另一個對象的引用,如果該對象是您已經碰撞的se,則忽略第二個對象。然后在下一個
FixedUpdate
調用中簡單地重置該字段。例如。