/* Note to pastebin viewers */
/* Create a PictureBox on your form and set Dock property to full */
/* Rename created PictureBox to pb */
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 SimpleAnimation
{
public partial class Form1 : Form
{
///
/// Store information about balls. Positions, speeds etc
///
List balls = new List();
///
/// Set event handlers
///
public Form1()
{
InitializeComponent();
pb.MouseDown += new MouseEventHandler(pb_MouseDown);
pb.Paint += new PaintEventHandler(pb_Paint);
}
///
/// Updates and draw balls on screen
///
///
///
void pb_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString("Left click to create a ball", SystemFonts.DefaultFont, Brushes.Black, new PointF(15, 15));
e.Graphics.DrawString("Right click to remove last ball", SystemFonts.DefaultFont, Brushes.Black, new PointF(15, 30));
for (int i = 0; i < balls.Count; i++)
{
Ball b = balls[i];
//Screen bounds
int top = 0;
int right = pb.Width - b.Size;
int bottom = pb.Height - b.Size;
int left = 0;
//Left wall
if (b.PosX < left)
{
b.PosX = left;
b.VelX *= -1;
}
//Right wall
if (b.PosX > right)
{
b.PosX = right;
b.VelX *= -1;
}
//Top wall
if (b.PosY < top)
{
b.PosY = top;
b.VelY *= -1;
}
//Bottom wall
if (b.PosY > bottom)
{
b.PosY = bottom;
b.VelY *= -1 + 0.5f; // Add a bounce
}
//Gravity
if (b.PosY < bottom)
{
b.VelY += 0.25f;
}
//Update positions
b.PosX += b.VelX;
b.PosY += b.VelY;
//Draw ball
e.Graphics.FillEllipse(Brushes.Black, b.PosX, b.PosY, b.Size, b.Size);
balls[i] = b;
}
}
///
/// Left click - Create ball
/// Right click - Remove last ball
///
///
///
void pb_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
balls.Add(new Ball(e.X-(Ball.DEFAULT_SIZE/2), e.Y-(Ball.DEFAULT_SIZE/2), 0, 1));
}
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
if (balls.Count > 0)
{
balls.RemoveAt(balls.Count - 1);
}
}
}
///
/// Setup game timer to run every 10 ms
///
///
///
private void Form1_Load(object sender, EventArgs e)
{
Timer gameTimer = new Timer();
gameTimer.Tick += new EventHandler(gameTimer_Tick);
gameTimer.Interval = 10;
gameTimer.Enabled = true;
}
///
/// Game timer tick, redraw picture box
///
///
///
void gameTimer_Tick(object sender, EventArgs e)
{
pb.Invalidate();
}
}
public class Ball
{
public float PosX { get; set; }
public float PosY { get; set; }
public float VelX { get; set; }
public float VelY { get; set; }
public int Size { get; set; }
public const int DEFAULT_SIZE = 25;
public Ball(int x, int y, int speedx, int speedy, int size = DEFAULT_SIZE)
{
PosX = x;
PosY = y;
VelX = speedx;
VelY = speedy;
Size = size;
}
}
}