【发布时间】: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,即角色精灵的宽高大小。