簡體   English   中英

兩個無法使用C#格式的圖片框之間的碰撞檢測

[英]Collision detection between two picture boxes not working c# form

嗨,我正在開發一個包含兩個圖片框,一個紅色框和一個藍色框的游戲。 藍色框由玩家控制,目標是與紅色框碰撞,該紅色框每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;
        }

    }
}

您需要在每次按鍵時檢查碰撞。 嘗試這個:

    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 
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM