MonoGame中碰撞检测矩形的起源

时间:2017-02-03 07:16:12

标签: c# xna monogame

我在游戏中遇到2D碰撞检测的麻烦。
问题是我的玩家的矩形没有正确地记录与其他物体的矩形的交点。

我想知道我用来旋转播放器的原始变量是否与我的问题有关,以及我如何解决它。

我将更详细地解释这个问题,但这是我的代码: 注意:Origin的类型为Vector2,角度为float类型,所有碰撞矩形的类型为Rectangle。

//Player.Update method

        //origin needs to be in update, because position of source changes for every frame of animation
        origin = new Vector2(Width / 2, Height / 2);
        playerDirection = new Vector2((float)Math.Sin(angle), (float)Math.Cos(angle));

        //Updating the position of my collision rectangle
        collisionRect.X = (int)position.X;
        collisionRect.Y = (int)position.Y;

        //Changing the values of angle while key is pressed
        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            angle -= 0.05f;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            angle += 0.05f;
        }
        //Updating player's position
        if (Keyboard.GetState().IsKeyUp(Keys.X))
        {
            keyPress = false;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.W))
        {
            position -= playerDirection * Speed;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.S))
            position += playerDirection * Speed;
        //Checking for collision detection with background objects
        if(BackgroundMaker.collisionPositions.Count >= 1)
        {
            foreach(Rectangle colPos in BackgroundMaker.collisionPositions)
            {
                if(collisionRect.Intersects(colPos))
                {
                    if (collisionRect.X < colPos.Right)
                        position.X = colPos.Right;
                }
            }
        }
    }
}

这段代码存在的问题是,我的玩家只有在中途时才与墙碰撞。我还没有实现右侧,上侧和下侧的碰撞,仅针对左侧。

以下是它的样子: enter image description here

提前感谢能够帮助我回答这个问题的任何人。 如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

您的代码正在按照您的指示工作

if (collisionRect.X < colPos.Right)
    position.X = colPos.Right;

在这里你要检查,如果碰撞盒的中间小于物体的右侧,则将玩家中间位置设置在物体的右侧,因此玩家的中间位置不能超过物体它是相交的。

然而,这并不考虑球员的宽度

您需要调整代码以使其更像这样:

float halfWidth = 16.0f; // ideally add a width to the player class and divide by 2
if (collisionRect.X - halfWidth < colPos.Right)
    position.X = colPos.Right + halfWidth;