我被困在试图弄清楚如何改变我的碰撞检测以使其正常工作,我将所有墙壁对象堆叠在一个列表中,然后当玩家移动时,我循环遍历每个墙壁对象并调用 DetectCollision 方法,这将返回 true 或 false取决于物体是否在墙内。
墙壁检测碰撞(X和Y坐标是墙壁的位置)
public bool DetectCollision(float x, float y)
{
if ((x >= this.XCoordinate && x <= (this.XCoordinate + this.BlockWidth)) && (y >= this.YCoordinate && y <= (this.YCoordinate + this.BlockHeight)))
return true;
else
return false;
}
因此,在我的播放器功能中,当玩家尝试移动时,我将移动添加到临时 X、Y 坐标并检查它们是否与墙壁碰撞,如果它们什么也没发生,否则我移动播放器。
但我注意到它不能正常工作,如果我在游戏场内添加一块墙,它只会检查右下角的碰撞检测?
玩家移动方式:
float x, y;
if (direction == Direction.E)
{
x = LiveObjects.player.XCoordinate - MovementSpeed;
y = LiveObjects.player.YCoordinate;
}
else if (direction == Direction.W)
{
x = LiveObjects.player.XCoordinate + MovementSpeed;
y = LiveObjects.player.YCoordinate;
}
else if (direction == Direction.N)
{
x = LiveObjects.player.XCoordinate;
y = LiveObjects.player.YCoordinate - MovementSpeed;
}
else
{
x = LiveObjects.player.XCoordinate;
y = LiveObjects.player.YCoordinate + MovementSpeed;
}
if (GameMechanics.DetectWallCollision(x, y) || GameMechanics.DetectWallCollision((x + LiveObjects.player.BlockWidth), (y + LiveObjects.player.BlockHeight))
{
OnPlayerInvalidMove(null, new PlayerEventArgs());
return;
}
DetectWallCollision 的循环只是:
foreach (Wall wall in LiveObjects.walls)
{
if (wall.DetectCollision(x, y))
return true;
}
return false;
有任何想法吗?