所以我的碰撞检测工作正常,但由于某种原因,玩家似乎先将地面介入1帧,然后在下一帧中跳出它,然后按照预期的那样跌落。
我用于碰撞检测的代码
void DoCollisions()
{
onGround = false;
Position.Y += Velocity.Y;
Vector2 tileCollision = GetTileCollision();
if (tileCollision.X != -1 || tileCollision.Y != -1)
{
onGround = true;
Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
new Rectangle(
tileCollision.X * World.tileEngine.TileWidth,
tileCollision.Y * World.tileEngine.TileHeight,
World.tileEngine.TileWidth,
World.tileEngine.TileHeight
)
);
Position.Y -= Velocity.Y;
Velocity.Y = 0;
Position.Y += collisionDepth.Y;
}
Position.X += Velocity.X;
tileCollision = GetTileCollision();
if (tileCollision.X != -1 || tileCollision.Y != -1)
{
Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
new Rectangle(
tileCollision.X * World.tileEngine.TileWidth,
tileCollision.Y * World.tileEngine.TileHeight,
World.tileEngine.TileWidth,
World.tileEngine.TileHeight
)
);
Position.X -= Velocity.X;
Velocity.X = 0;
Position.X += collisionDepth.X;
}
}
Vector2 GetTileCollision()
{
int topLeftTileX = (int)(CollisionRectangle.TopLeft.X / World.tileEngine.TileWidth);
int topLeftTileY = (int)(CollisionRectangle.TopLeft.Y / World.tileEngine.TileHeight);
int BottomRightTileX = (int)(CollisionRectangle.DownRight.X / World.tileEngine.TileWidth);
int BottomRightTileY = (int)(CollisionRectangle.DownRight.Y / World.tileEngine.TileHeight);
for (int i = topLeftTileX; i <= BottomRightTileX; i++)
{
for (int j = topLeftTileY; j <= BottomRightTileY; j++)
{
if (World.tileEngine.TileIsSolid(i, j))
{
return new Vector2(i,j);
}
}
}
return new Vector2(-1,-1);
}
答案 0 :(得分:2)
仅使用Y
方向作为示例,乍一看似乎您正在调整Y
两次,一次在碰撞检查之前,然后当您发生碰撞时,您将恢复{{1并按Y
你可能不应该恢复collisionDepth
,如果collisionDepth.Y表明你正在与地面相交,那么你应该将你的物体推回深度,这会让你冲到地面。 / p>
Y