我只想做一個抽象的方法稱爲相撞身體對象:
abstract class Body
{
abstract void Collision(Body other);
}
class Dog : Body
{
public override void Collision(Body other) {
this.Bark();
}
public void Bark() { ... }
}
然後在你的防撞功能只是呼叫衝突的參與機構。
public bool OnCollision(Body body1, Body body2)
{
body2.Collision(body2);
}
這樣,任何類型的體都可以做任何它需要當碰撞發生時,你甚至可以優化這種以跟蹤哪些機構已與海誓山盟通知碰撞和數量減少的函數調用你必須執行:
public bool OnCollision(Body body1, Body body2)
{
// Record that these two objects have been notified of a collision
// then when these same objects are the only two operands in subsequent calls
// you can just short circuit the calls.
if(!AlreadyNotifiedOfCollision(body1, body2))
{
body1.Collision(body2);
body2.Collision(body1);
NotifiedOfCollision(body1, body2);
}
}
當然實證檢驗都必須做驗證此檢查是不是其實只是在做電話快兩倍......
謝謝我沒有意識到這一點!這非常有幫助。 – 2008-12-18 20:34:06