I am working on a breakout game using c# and gdi+. I am unsure of how to implement the collision detection between the ball and the bricks. I am thinking about using a list function.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private static System.Timers.Timer aTimer;
int xstep = 5;
int ystep = 5;
int x1 = 0;
int y1 = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.DoubleBuffered = true;
this.Paint += new PaintEventHandler (Form1_Paint);
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
aTimer = new System.Timers.Timer(50);
aTimer.Elapsed += new ElapsedEventHandler(timer1_Tick);
aTimer.Start();
}
int move_paddle = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
move_paddle-=5;
if(move_paddle <= -320)
{
move_paddle = -320;
}
break;
case Keys.Right:
move_paddle+=5;
if(move_paddle >= 320)
{
move_paddle = 320;
}
break;
default:
return;
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Black, 0, 0, 1104, 768);
e.Graphics.DrawImage(Properties.Resources.paddle, new Rectangle(320+move_paddle, 425, 80, 40));
this.Invalidate();
for (int i = 0; i <= 480; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.red, new Rectangle(i, 0, 80, 40));
}
for (int i = 80; i <= 560; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.green, new Rectangle(i, 0, 80, 40));
}
for (int i = 160; i <= 640; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.blue, new Rectangle(i, 0, 80, 40));
}
for (int i = 0; i <= 480; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.green, new Rectangle(i, 40, 80, 40));
}
for (int i = 80; i <= 560; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.blue, new Rectangle(i, 40, 80, 40));
}
for (int i = 160; i <= 640; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.red, new Rectangle(i, 40, 80, 40));
}
for (int i = 0; i <= 480; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.blue, new Rectangle(i, 80, 80, 40));
}
for (int i = 80; i <= 560; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.red, new Rectangle(i, 80, 80, 40));
}
for (int i = 160; i <= 640; i += 240)
{
e.Graphics.DrawImage(Properties.Resources.green, new Rectangle(i, 80, 80, 40));
}
e.Graphics.DrawImage(Properties.Resources.bullet, new Rectangle(355 + x1, 232 + y1, 10, 10));
}
private void timer1_Tick(object sender, EventArgs e)
{
if (x1 >= 360 || x1 <= -360)
{
xstep = -xstep;
}
if (y1 >= 227 || y1 <= -232)
{
ystep = -ystep;
}
x1 += xstep;
y1 += ystep;
}
}
}