更快的碰撞检查算法

时间:2011-08-26 15:58:54

标签: collision-detection

这是我现在使用的代码:

For Local i : Int = 0 To Entity.Entities.Count() - 1
        For Local j : Int = 0 To Entity.Entities.Count() - 1
            If j = i Or Not Entity(Entity.Entities.ValueAtIndex(i)).IsPhyicsEnabled Or Not Entity(Entity.Entities.ValueAtIndex(j)).IsPhyicsEnabled
                Continue
            EndIf

            Local a : Entity = Entity(Entity.Entities.ValueAtIndex(i));
            Local b : Entity = Entity(Entity.Entities.ValueAtIndex(j));

            Local dist : Float = Sqr(((a.Position.X - b.Position.X)^2) + ((a.Position.Y - b.Position.Y)^2))

            If dist < Min(a.Radius, b.Radius)
                a.Collide(b)
            EndIf
        Next
    Next

问题在于循环。检查的次数太多了。有没有办法可以减少它?

2 个答案:

答案 0 :(得分:1)

试试这个:

For Local i : Int = 0 To Entity.Entities.Count() - 1
    If Not Entity(Entity.Entities.ValueAtIndex(i)).IsPhyicsEnabled
        Continue
    EndIf

    Local a : Entity = Entity(Entity.Entities.ValueAtIndex(i));
    Local aRadiusSquared = a.Radius^2

    For Local j : Int = (i+1) To Entity.Entities.Count() - 1
        If Not Entity(Entity.Entities.ValueAtIndex(j)).IsPhyicsEnabled
            Continue
        EndIf

        Local b : Entity = Entity(Entity.Entities.ValueAtIndex(j));

        Local distSquared : Float = ((a.Position.X - b.Position.X)^2) + ((a.Position.Y - b.Position.Y)^2)

        If distSquared < Min(aRadiusSquared, b.Radius^2)
            a.Collide(b)
        EndIf
    Next
Next

答案 1 :(得分:0)

我强烈推荐“游戏物理引擎开发:如何为您的游戏制作一个强大的商业级物理引擎”(长标题,但准确)。该网站和GitHub网页完全维护,AFAICT。老实说,那里的代码比书的代码要好得多,至少就我的情况而言。