[英]Collision detection between two picture boxes not working c# form
Hi I'm working on a game that involves two picture boxes, a red box and a blue box. 嗨,我正在开发一个包含两个图片框,一个红色框和一个蓝色框的游戏。 The blue box is controlled by the player and the goal is to collide with the red box, which teleports to a random location every 5 seconds.
蓝色框由玩家控制,目标是与红色框碰撞,该红色框每5秒传送到一个随机位置。 My problem is getting a collision between the red and blue box.
我的问题是红色和蓝色框之间发生冲突。 On collision the red box is to teleport to a random location but that isn't happening.
发生碰撞时,红色框将被传送到随机位置,但这没有发生。
heres my code: 这是我的代码:
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;
}
}
}
You need to check the collision each time a key is pressed. 您需要在每次按键时检查碰撞。 Try this:
尝试这个:
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
}
}
Note: A better way would be checking the collision when the red box re positions itself too, as there can be a condition when the red box bangs into the blue one. 注意:一种更好的方法是在红色框也重新定位时检查碰撞,因为在红色框撞击蓝色框时可能会出现某种情况。
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.