【问题标题】:Collision detection between two picture boxes not working c# form两个图片框之间的碰撞检测不起作用c#表单
【发布时间】:2016-05-20 17:33:28
【问题描述】:

您好,我正在开发一款包含两个图片框、一个红色框和一个蓝色框的游戏。蓝色方块由玩家控制,目标是与红色方块发生碰撞,红色方块每 5 秒传送到一个随机位置。我的问题是红色和蓝色框之间发生碰撞。碰撞时,红色框会传送到随机位置,但不会发生。

这是我的代码:

namespace block_game
{
    public partial class Form1 : Form
    {

        public Form1()
        {

            InitializeComponent();
            KeyDown += new KeyEventHandler(Form1_KeyDown);

            if (blue_box.Bounds.IntersectsWith(red_box.Bounds))
            {
                Tele();
            }


        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = blue_box.Location.X;
            int y = blue_box.Location.Y;

            if (e.KeyCode == Keys.Right) x += 10;
            else if (e.KeyCode == Keys.Left) x -= 10;
            else if (e.KeyCode == Keys.Up) y -= 10;
            else if (e.KeyCode == Keys.Down) y += 10;

            blue_box.Location = new Point(x, y);
        }
        public Random r = new Random();
        private void tmrTele_Tick(object sender, EventArgs e)
        {
            tmrTele.Interval = 5000;
            Tele();
        }

        private void Tele()
        {
            int x = r.Next(0, 800 - red_box.Width);
            int y = r.Next(0, 500 - red_box.Width);
            red_box.Top = y;
            red_box.Left = x;
        }

    }
}

【问题讨论】:

  • 你似乎只在开始时检查碰撞

标签: c# winforms visual-studio


【解决方案1】:

您需要在每次按键时检查碰撞。 试试这个:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int x = blue_box.Location.X;
        int y = blue_box.Location.Y;

        if (e.KeyCode == Keys.Right) x += 10;
        else if (e.KeyCode == Keys.Left) x -= 10;
        else if (e.KeyCode == Keys.Up) y -= 10;
        else if (e.KeyCode == Keys.Down) y += 10;

        blue_box.Location = new Point(x, y);
        if (blue_box.Bounds.IntersectsWith(red_box.Bounds))
        {
            //your logic to handle the collision 
        }
    }

注意:更好的方法是在红框自身重新定位时检查碰撞,因为可能存在红框撞到蓝色框的情况。

    private void Tele()
    {
        int x = r.Next(0, 800 - red_box.Width);
        int y = r.Next(0, 500 - red_box.Width);
        red_box.Top = y;
        red_box.Left = x;

        if (blue_box.Bounds.IntersectsWith(red_box.Bounds))
        {
            //your logic to handle the collision 
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2018-10-09
    • 2023-03-05
    • 2013-07-22
    相关资源
    最近更新 更多