You need to write the code for checking the bounds (which you have now written in Form1_Load) in a separate function and call it from timer1_Tick
Collision detection between PictureBoxes in C#
-
28-06-2023 - |
Question
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; 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");
}
}
}
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow