2009-06-12 17 views
1

對於我正在構建的物理引擎,我需要快速確定兩個剛體是否在前一幀接觸。我希望它儘可能快,所以也許你們可以提供一些想法?聯繫圖

這是我到目前爲止。 (和它的作品不錯,但整個事情讓我想知道我怎麼能改善它。)

// I thought using a struct would be a good idea with only two values? 
    struct Contact 
    { 
     public readonly PhyRigidBody Body1; 
     public readonly PhyRigidBody Body2; 

     public Contact(PhyRigidBody body1, PhyRigidBody body2) 
     { 
      Body1 = body1; 
      Body2 = body2; 
     } 
    } 

    class ContactComparer : IEqualityComparer<Contact> 
    { 
     public bool Equals(Contact x, Contact y) 
     { 
      // It just have to be the two same bodies, nevermind the order. 
      return (x.Body1 == y.Body1 && x.Body2 == y.Body2) || (x.Body1 == y.Body2 && x.Body2 == y.Body1); 
     } 

     public int GetHashCode(Contact obj) 
     { 
      // There has got to be a better way than this? 
      return RuntimeHelpers.GetHashCode(obj.Body1) + RuntimeHelpers.GetHashCode(obj.Body2); 
     } 
    } 

    // Hold all contacts in one big HashSet. 
    private HashSet<Contact> _contactGraph = new HashSet<Contact>(new ContactComparer()); 



    // To query for contacts I do this 
    Contact contactKey = new Contact(body1, body2); 
    bool prevFrameContact = _contactGraph.Remove(contactKey); 
    // ... and then I re-insert it later, if there is still contact. 

回答

1

你也可以使用一個Dictionary<PhyRigidBody, HashSet<PhyRigidBody>>給定身體映射到一組其他機構是接觸的(這意味着你保持每個「聯繫人」兩次,因爲每個人都包含在另一個聯繫人中)。這將完全避免Contact結構,以及有點腥意的Equals方法。我不確定這是一種改進,但值得考慮。

+0

如何提取擴展或類級別的方法,「聯繫」PhyRigidBody - 即布爾聯繫= somePhyRigidBody.Contact(anotherObject)。更好的是,如果你以後想要實現非剛體物理,你應該考慮使Contact()方法成爲接口的一部分,這樣你就可以輕鬆擴展你的庫。 – 2009-06-12 18:45:50

+0

我認爲你在這裏混淆了兩個不同的問題:如何確定聯繫人確實應該到達可以被覆蓋的地方(如界面等)。但這傢伙正在詢問如何*存儲*前一幀的聯繫數據,據推測*在計算之後*。 – Avish 2009-06-12 19:08:53

0

我很困惑這個:

// It just have to be the two same bodies, nevermind the order. 
return (x.Body1 == y.Body1 && x.Body2 == y.Body2) || (x.Body1 == y.Body2 && x.Body2 == y.Body1); 

但總體來說,我不明白這一點。那裏有多少個屍體?身體是否會移動,以便經常改變他們的接觸變化?你可以把它們放入一個空間網格嗎?你多久需要知道接觸是什麼?

不知道更多關於這個問題很難說太多,儘管我的直覺是讓所有的哈希代碼和數據結構都要花費大量時間。