2
Reply

Animating Rectangles to make them move around the screen randomly

Andrej Nikovic

Andrej Nikovic

Sep 27 2011 3:43 PM
3k
Hi guys,

Im new to C# and am trying to make a little program where when i click a button it creates a rectangle that will bounce around the screen randomly and perhaps change colour (but the main thing is to make it bounce randomly first). I've got some code that draws a rectangle in a picturebox but I have no idea how to code the resulting rectangle to move around. Also I've been told I should put the rectangles in a separate class but I'm not sure if I should or not. Here's a snippet of my code that draws a rectangle at position 0,0 when i click a buttion "H".

namespace Lines1
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }
 private System.Drawing.Graphics g;
 private System.Drawing.Pen pen1 = new System.Drawing.Pen(Color.Blue, 2F);

 private voide button1_Click(object sender, EventArgs e)
 {
 g = PictureBox1.CreateGraphics();
 g.DrawRectangle(pen1,0,0,30,30);
 }

 private voide PictureBox1_Click(object sender, EventArgs e)
 {
 }
}
}

I have code doing other things but this is all that draws a rectangle and its in the Form1 class.
Any help would be appreciated,
Thanks.
 
Edit: I should of mentioned im using visual studio 2010

Answers (2)