我试图创建一个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
发布于 2012-01-30 02:08:17
我不确定这是否导致了整个问题。但是在第三次检查(检查下面的瓷砖)时,您将再次检查上面的瓷砖。
这里的这一部分:
tile = map.Tiles[(int)curTitle.Y + 1, (int)curTitle.X];在下一行中,testRect的params中仍然有这样的内容:
((int)curTitle.Y - 1) * map.TileSize应:
((int)curTitle.Y + 1) * map.TileSize全校正片段:
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;希望这有所帮助:)
发布于 2012-01-25 09:19:24
这句话在我看来很奇怪:
testRect = new Rectangle(
((int)curTitle.X) * map.TileSize,
((int)curTitle.Y) * map.TileSize,
map.TileSize,
map.TileSize);你为什么把X和Y坐标与TileSize相乘?
我不知道Rectangle的参数是什么意思,但我假设前两个是位置,最后两个是宽度和高度。我想你是想写
testRect = new Rectangle(
((int)curTitle.X),
((int)curTitle.Y),
map.TileSize,
map.TileSize);https://stackoverflow.com/questions/8999973
复制相似问题