所以我让我的碰撞检测工作,但由于某种原因,玩家似乎进入地面 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);
}