我一直在试图弄清楚如何改变我的碰撞检测以使其正常工作,我将所有墙对象堆叠在一个列表中,然后当玩家移动时我循环遍历每个墙对象并调用 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 坐标并检查它们是否与墙壁发生碰撞,如果它们什么也没发生,否则我移动玩家。
但我注意到它不能正常工作,如果我在游戏区内添加一 block 墙,它只会检查右下角的碰撞检测吗?
玩家移动方式:
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;
有什么想法吗?
最佳答案
我假设在您的世界中没有任何东西是无限小的(即像素大小)。要实现真正的边界框碰撞,您必须考虑两个对象的大小,而不仅仅是一个。
boolean intersectsEntity(Entity e)
{
return (e.position.x <= position.x + size.x) &&
(e.position.y <= position.y + size.y) &&
(e.position.x + e.size.x >= position.x) &&
(e.position.y + e.size.y >= position.y);
}
这当然是假设一个实体有一个向量来表示它的位置和它的大小。所以 size.x == 宽度,size.y == 高度。
关于C# 二维碰撞检测问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1298999/