C# 矩形碰撞检测无法正常工作

C# Rectangle Collision Detection not working as it is supposed to

大家好,我正在用 C#/XNA 制作一个小游戏 我遇到了碰撞问题。

基本上我在我的代码中所做的是我做了一个普通的玩家移动,而不是仅仅检查例如向上键是否被按下,它还检查玩家是否 CanGoTop == true;

if (keyState.IsKeyDown(Keys.Up) && CanGoTop == true) 
{
bla bla bla
}

我对左、右、上、下执行此操作,如果 bollean 为假,玩家将不会移动(在这 4 个 movemnt 语句之后有一个 else 语句将速度、x 和 .y 设置为 0 )

现在我在我的 Player class 中创建了一个方法,你会明白的 只是简单地看一下它是什么,我认为我不必解释这里发生了什么:

        public void RectangleInteraction(Rectangle anotherRectangle)
    {
        if (playerRectangle.Bottom <= anotherRectangle.Top &&
            playerRectangle.Top >= (anotherRectangle.Top - playerRectangle.Height) &&
            playerRectangle.Left <= anotherRectangle.Right &&
            playerRectangle.Right >= anotherRectangle.Left)
        {
            CanGoBot = false;
        }
        else CanGoBot = true;


        if (playerRectangle.Top >= anotherRectangle.Bottom &&
            playerRectangle.Bottom <= (anotherRectangle.Bottom + playerRectangle.Height) &&
            playerRectangle.Left <= anotherRectangle.Right &&
            playerRectangle.Right >= anotherRectangle.Left)
        {
            CanGoTop = false;
        }
        else CanGoTop = true;


        if (playerRectangle.Top <= anotherRectangle.Bottom &&
            playerRectangle.Bottom >= anotherRectangle.Top &&
            playerRectangle.Right <= anotherRectangle.Left &&
            playerRectangle.Left >= (anotherRectangle.Left - playerRectangle.Width))
        {
            CanGoRight = false;
        }
        else CanGoRight = true;


        if (playerRectangle.Top <= anotherRectangle.Bottom &&
            playerRectangle.Bottom >= anotherRectangle.Top &&
            playerRectangle.Left >= anotherRectangle.Right &&
            playerRectangle.Right <= (anotherRectangle.Right + playerRectangle.Width))
        {
            CanGoLeft = false;
        }
        else CanGoLeft = true;

    }

然后在我的 Game1.cs Update() 方法中,我使用我的播放器实例在那里调用该方法,现在这让我很烦恼,它适用于 CanGoLeft 但适用于其他3 个布尔值,它没有。

我真的不知道为什么,这是我使用 InGameMsgs 的 4 个屏幕截图来帮助我解决问题,并且用我的代码检查这些消息告诉我 CollisionLogic 很好,但还有其他问题。 为什么只有 CanGoLeft 有效呢? :/

在此先感谢您的宝贵时间和帮助。

你的逻辑似乎有几个地方是错误的。您应该使用 Rectangle 的方法,例如 Offset and Intersects 来检查目标 Rectangle 是否会发生碰撞。我认为这接近您的意图(假设 distance 是您玩家移动的值):

public void RectangleInteraction(Rectangle anotherRectangle)
{
    Rectangle down = playerRectangle; down.Offset(0, distance);
    Rectangle up = playerRectangle; up.Offset(0, -distance);
    Rectangle left = playerRectangle; left.Offset(-distance, 0);
    Rectangle right = playerRectangle; right.Offset(distance, 0);

    ConGoBot = !down.Intersects(anotherRectanlge); 
    ConGoTop = !up.Intersects(anotherRectanlge); 
    ConGoLeft = !left.Intersects(anotherRectanlge); 
    ConGoRight = !right.Intersects(anotherRectanlge); 
}

(假设您使用的是 Microsoft.Xna.Framework.Rectangle, there are other Rectangle structs in .net framework, but your question was tagged