简体   繁体   English

C#中PictureBox之间的碰撞检测

[英]Collision detection between PictureBoxes in C#

I've 2 pictureboxes on my Form, One is a moving one, whose directions are controlled by the keys, and other is a stable one, How is it possible to detect a collision between them.....Here is what I've tried; 我的窗体上有2个图片框,一个是移动的,其方向由按键控制,另一个是稳​​定的,如何检测它们之间的碰撞.....这就是我尝试过 but failed..... 但是失败了.....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        private enum disha { up, down, left, right };
        private disha ekdisha = disha.down;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                ekdisha = disha.up;
            }
            else if (e.KeyCode == Keys.Down)
            {
                ekdisha = disha.down;
            }
            else if (e.KeyCode == Keys.Left)
            {
                ekdisha = disha.left;
            }
            else if (e.KeyCode == Keys.Right)
            {
                ekdisha = disha.right;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (pictureBox1.Top <= 0)
            {
                pictureBox1.Top = 0;
            }


            if (ekdisha == disha.up)
            {
                pictureBox1.Top -= 3;
            }

            else if (ekdisha == disha.down)
            {
                pictureBox1.Top += 3;
            }

            else if (ekdisha == disha.left)
            {
                pictureBox1.Left -= 3;
            }

            else if (ekdisha == disha.right)
            {
                pictureBox1.Left += 3;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (pictureBox2.Bounds.IntersectsWith(pictureBox1.Bounds))
            {
                MessageBox.Show("Something is collided");
            }
        }
    }

} }

您需要在单独的函数中编写用于检查范围的代码(现在已经在Form1_Load中编写),然后从timer1_Tick调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM