2D矩形碰撞检测系统(适用于真实游戏)

时间:2011-02-07 20:07:37

标签: c# xna collision-detection

过去几个月我一直在闲暇时间开发游戏。我一遍又一遍地重新实现并且没有100%工作的一个关键点是碰撞检测。我的系统(在下面发布)主要是有效的,但是随机的东西似乎时不时发生,比如玩家被推到了关卡的范围之外等等。我遇到过的问题的教程似乎提供了基本的工作方式,即你有要知道一个物体与所讨论的物体有关,但在真实的游戏中你根本不会知道这一点。这是我的实现,但我所追求的是,​​如果有人知道一个良好的实体系统来实现我在这里所做的事情。

请注意,item来自IItem的集合,它为每个项目公开Rectangle和一些其他位。

    public void Move(float xAdditional, float yAdditional)
    {
        X += xAdditional;
        Y += yAdditional;

        foreach (var item in Level.Items)
        {
            if (item != this)
            {
                if (item.Boundary.Intersects(this.Boundary))
                {
                    if (item.Boundary.Top > this.Boundary.Top) //we have collided with an object below us.
                    {
                        Y = item.Boundary.Top - (this.Boundary.Height/2);
                    }
                    if(item.Boundary.Bottom < this.Boundary.Bottom)//we have collided with an object above us.
                    {
                        Y = item.Boundary.Bottom + (this.Boundary.Height/2);
                    }
                    if(item.Boundary.Left > this.Boundary.Left) //We have collided with an object to the right.
                    {
                        X = item.Boundary.Left - (this.Boundary.Width/2);
                    }
                    if(item.Boundary.Right < this.Boundary.Right)// We have collided with an object to the left;
                    {
                        X = item.Boundary.Right + (this.Boundary.Width/2);
                    }
                }
            }

        }


    }

2 个答案:

答案 0 :(得分:1)

最终的解决方案是放弃我自己的解决方案并实施Farseer

由于

经过一段时间后,我选择了physics2d.net,从开发人员的角度来看,我发现它更有用。

答案 1 :(得分:0)

首先,碰撞检测在很大程度上取决于对象的几何形状。 有多种经过验证的工作解决方案可用于线性代数数学, 但它们取决于您尝试使用的几何形状。而不是 使用对象属性实现算法尝试直接实现数学方程式,然后使用结果确定是否发生了碰撞。 (比如使用向量t = a-b,如果| t |&gt; 0碰撞,否则不行)。

如果你有一个简单的几何形状,如矩形或圆形,你应该采取 研究'3D游戏编程的数学&amp; Eric的计算机图形学 Lengyel的。

另请注意,您可以使用其他方法实现碰撞检测 喜欢精灵碰撞。另一种可能性是使用更高级别的框架 为你做这项工作(例如OSG)