【发布时间】:2018-09-13 02:31:40
【问题描述】:
我正在使用 Monogame 编写基于 2D 瓷砖的游戏中的碰撞编码。我遇到了一个问题,如果我的玩家一次站在 2 个瓷砖上,它会开始抽搐,因为碰撞解决运行了 2 次,我希望它只运行一次。我该怎么做?这是我的代码:
public void HandleCollisions()
{
Rectangle plyRect = ply.GetBounds(); //get player rectangle
Vector2 currentPos = new Vector2(plyRect.X, plyRect.Y); //get player current position
Vector2 xy = new Vector2( (float)Math.Floor((ply.pos.X + ply.tex.Width) / world.tileSize),
(float)Math.Floor((ply.pos.Y + ply.tex.Height) / world.tileSize)); //get tiles position based on player position
for (int x = (int)xy.X - 4; x <= (int)xy.X + 4; x++) //run through tiles near the player
{
for (int y = (int)xy.Y - 4; y <= (int)xy.Y + 4; y++)
{
if (x >= 0 && y >= 0 && x < world.GetWorldSize().X && y < world.GetWorldSize().Y) //check if tiles are within map
{
if (world.tiles[x, y] != null)
{
if (world.tiles[x, y].collision == Tile.Collision.SOLID) //check if tile is solid
{
Rectangle tileRect = world.tiles[x, y].GetRect(); //get the tiles rectangle
if (plyRect.Intersects(tileRect)) //check if intersecting
{
Vector2 depth = RectangleExtension.GetIntersectionDepth(plyRect, tileRect); //get intersecting depth
if (depth != Vector2.Zero)
{
float absDepthX = Math.Abs(depth.X);
float absDepthY = Math.Abs(depth.Y);
if (absDepthY < absDepthX)
{
currentPos = new Vector2(currentPos.X, currentPos.Y + depth.Y); //resolve Y collision first
}
else
{
currentPos = new Vector2(currentPos.X + depth.X, currentPos.Y); //then resolve X collision
}
}
}
}
}
}
}
}
ply.pos = currentPos; //set player position after the checking is done
}
【问题讨论】:
-
“交叉深度”返回什么?可能与此相关,因为这些可能是浮点值。例如,
if (depth != Vector2.Zero)可能在depth == 0.000001时返回 true 此外,currentPos.Y + depth.Y 可能并不总是准确地产生 0