我正在尝试创建一个 pacman 游戏来学习 XNA,但我在让碰撞检测工作时遇到了一些问题。游戏是基于瓷砖的,其中 1 是墙,0 是可步行的。然后它会使用你所在的瓷砖加上它周围的 4,如果它与其中一个碰撞并且瓷砖值不为 0,它将重置位置到移动之前的位置。但是由于某种原因它不起作用,它会随机卡住,有时我什至可以穿过墙壁移动。
这是我的碰撞检测:
var oldPos = Position;
// Updates the Position
base.Update(theGameTime, mSpeed, mDirection);
// Test Collidetion
Rectangle objRect = new Rectangle((int)Position.X, (int)Position.Y, 32, 32);
bool isCollided = false;
Vector2 curTitle = GetCurrentTitle();
// Test UP, DOWN, LEFT, RIGHT
int tile;
Rectangle testRect;
if ((int)curTitle.Y < 0 || (int)curTitle.X < 0 || (int)curTitle.Y >= map.MapSizeWidth - 1 || (int)curTitle.X >= map.MapSizeHeight - 1)
isCollided = true;
if (!isCollided)
{
tile = map.Tiles[(int)curTitle.Y, (int)curTitle.X];
testRect = new Rectangle(((int)curTitle.X) * map.TileSize, ((int)curTitle.Y) * map.TileSize, map.TileSize, map.TileSize);
if (tile != 0 && rectangle_collision(testRect, objRect))
isCollided = true;
if (curTitle.Y != 0)
{
tile = map.Tiles[(int)curTitle.Y - 1, (int)curTitle.X];
testRect = new Rectangle(((int)curTitle.X) * map.TileSize, ((int)curTitle.Y - 1) * map.TileSize, map.TileSize, map.TileSize);
if (tile != 0 && rectangle_collision(testRect, objRect))
isCollided = true;
}
tile = map.Tiles[(int)curTitle.Y + 1, (int)curTitle.X];
testRect = new Rectangle(((int)curTitle.X) * map.TileSize, ((int)curTitle.Y - 1) * map.TileSize, map.TileSize, map.TileSize);
if (tile != 0 && rectangle_collision(testRect, objRect))
isCollided = true;
if (curTitle.X != 0)
{
tile = map.Tiles[(int)curTitle.Y, (int)curTitle.X - 1];
testRect = new Rectangle(((int)curTitle.X - 1) * map.TileSize, ((int)curTitle.Y) * map.TileSize, map.TileSize, map.TileSize);
if (tile != 0 && rectangle_collision(testRect, objRect))
isCollided = true;
}
tile = map.Tiles[(int)curTitle.Y, (int)curTitle.X + 1];
testRect = new Rectangle(((int)curTitle.X + 1) * map.TileSize, ((int)curTitle.Y) * map.TileSize, map.TileSize, map.TileSize);
if (tile != 0 && rectangle_collision(testRect, objRect))
isCollided = true;
}
if (isCollided)
Position = oldPos;
谁能看到为什么我的碰撞检测不起作用?
编辑:我已将整个项目上传到http://sogaard.us/Pacman.zip