【发布时间】:2009-06-13 22:21:15
【问题描述】:
对于我正在构建的物理引擎,我需要在前一帧快速确定两个刚体是否接触。我希望它尽可能快,所以也许你们可以提供一些想法?
这是我到目前为止所得到的。 (而且效果还不错,但整件事让我想知道如何改进它。)
// 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.
【问题讨论】:
标签: c# optimization