如何实现与“玩家”到“墙”的碰撞?

时间:2017-09-10 19:03:01

标签: c# collision-detection

我做了一个简单的游戏,并添加了碰撞,所以我的玩家不会走出窗外,它工作,我想制作一些墙壁,并为他们进行碰撞,但它没有工作/真的是马车。 有没有办法阻止“玩家”穿过墙壁是什么?

运动代码:

            if(e.KeyCode == Keys.A)
        {
            left = true;
        }

        if (e.KeyCode == Keys.D)
        {
            right = true;
        }

        if (e.KeyCode == Keys.W)
        {
            up = true;
        }

        if (e.KeyCode == Keys.S)
        {
            down = true;
        }
    }


    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        #region Stop controls
        if (e.KeyCode == Keys.A)
        {
            left = false;
        }

        if (e.KeyCode == Keys.D)
        {
            right = false;
        }

        if (e.KeyCode == Keys.W)
        {
            up = false;
        }

        if (e.KeyCode == Keys.S)
        {
            down = false;
        }
    }

我的外墙碰撞:

            if (right == true)
        {
            if (player.Left >= level.Width - player.Width)
            {
                player.Left = level.Width - player.Width;
            }
            else
            {
                player.Left += speed;
            }
        }

        if (left == true)
        {
            if (player.Left <= level.Left)
            {
                player.Left = level.Left;
            }
            else
            {
                player.Left -= speed;
            }
        }

        if (up == true)
        {
            if(player.Top <= level.Top)
            {
                player.Top = level.Top;
            }
            else
            {
                player.Top -= speed;
            }
        }

        if (down == true)
        {
            if (player.Top >= level.Bottom - player.Height)
            {
                player.Top = level.Bottom - player.Height;
            }
            else
            {
                player.Top += speed;
            }
        }

1 个答案:

答案 0 :(得分:1)

我读它就好像目前你使用整数值来确定玩家坐标以及外墙的边界。

你可以做的就是使用一个二维阵列。

数组中的数组,可以说是模仿坐标系。

然后你可以让每个阵列坐标都保持一个&#34; CellInformation&#34;对象

CellInformation对象会知道它是否可以步行,这意味着,例如,假设玩家处于坐标(4,4)并尝试向左移动到(3,4),他将在数组中选择数组4 3,从那里拿走物体然后询问它是否可以步行,如果是,玩家将他的新坐标设置为(3,4)。

然后,您还可以向每个单元格添加大量其他信息,例如,如果它是木质材料,水,熔岩,泥土,森林区域,是否存在敌人等等。

有关2D阵列的更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

相关问题