我在游戏中遇到2D碰撞检测有点麻烦 .
问题是我的玩家的矩形没有正确地记录与其他对象的矩形的交集 .
我想知道我用来旋转播放器的原始变量是否与我的问题有关,以及我如何解决它 .
我将更详细地解释这个问题,但这里首先是我的代码:注意:Origin是Vector2类型,angle是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;
}
}
}
}
}
这段代码的问题是,我的玩家只有在他中途穿过时才与墙碰撞 . 我没有实现右侧,上侧和下侧的碰撞,仅针对左侧 .
这是它的样子:
提前感谢能够帮助我回答这个问题的任何人 . 如果您需要更多信息,请告诉我 .