玩家在1个以上的方块上时发生碰撞抽动

时间:2018-09-12 18:26:51

标签: c# collision monogame

我正在用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
    }

1 个答案:

答案 0 :(得分:1)

一旦检测到一个冲突,就使用break中断for循环;声明