【问题标题】:Origin of Rectangle for Collision Detection in MonoGameMonoGame中碰撞检测的矩形原点
【发布时间】:2017-02-03 07:16:11
【问题描述】:

我的游戏中的 2D 碰撞检测有点问题。
问题是我的播放器的矩形没有正确注册与其他对象的矩形的交集。

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

我会更详细地解释这个问题,但首先是我的代码: 注意:原点是 Vector2 类型,角度是浮点类型,所有碰撞矩形都是 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;
                }
            }
        }
    }
}

这段代码的问题是,我的播放器只有在播放到一半时才会与墙壁发生碰撞。我还没有实现左右两侧的碰撞,只适用于左侧。

这是它的样子:

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

【问题讨论】:

  • 我建议您使用调试模式,在该模式下为玩家绘制碰撞框,这样发生的事情就会变得更加明显
  • 碰撞矩形的大小是多少?
  • @Ben 矩形的大小为32x32,即角色精灵的宽高大小。

标签: c# xna monogame


【解决方案1】:

您的代码按照您的指示运行

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;

【讨论】:

  • 感谢您的回答!我不知道 x 和 y 坐标对应于精灵的中间。我确定它们对应于左上角,因此将使用它创建矩形
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多