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;
namespace 两个小球移动
{
public partial class Form1 : Form
{
Ball b1 = new Ball(10, Color.Red), b2 = new Ball(10, Color.Green);
Graphics g;
Rectangle r;
const int step = 3;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
g = p1.CreateGraphics();
r.X =0;
r.Y =0;
r.Width = p1.Width;
r.Height = p1.Height;
b1.Move(10,10);
b2.Move(100, 100);
if (b1.IsContact(b2)) b2.Move(b2.X + 2*b2.R, b2.Y + 2*b2.R);
if (b1.DirectionX == b2.DirectionX && b1.DirectionY == b2.DirectionY) b1.DirectionX *= -1;
}
private void timer1_Tick(object sender, EventArgs e)
{
g.Clear(BackColor);
b1.EdgeProcessing(r);
b2.EdgeProcessing(r);
b1.Analysis(b2);
b1.Move(b1.X + b1.DirectionX * step, b1.Y + b1.DirectionY * step);
b2.Move(b2.X + b2.DirectionX * step, b2.Y + b2.DirectionY * step);
g.FillEllipse(new SolidBrush(b1.Color), new Rectangle(b1.X - b1.R, b1.Y - b1.R, 2 * b1.R, 2 * b1.R));
g.FillEllipse(new SolidBrush(b2.Color), new Rectangle(b2.X - b2.R, b2.Y - b2.R, 2 * b2.R, 2 * b2.R));
}
}
public class Ball
{
public int X { set; get; }
public int Y { set; get; }
public int DirectionX { set; get; }
public int DirectionY { set; get; }
public int R { set; get; }
public Color Color { set; get; }
public void Move(int a, int b) { X = a; Y = b; }
public Ball(int r, Color color)
{
R = r;
Color = color;
Random random = new Random((int)DateTime.Now.Ticks);
//开始的方向
if (random.Next() % 2 == 0) DirectionX = -1; else DirectionX = 1;
if (random.Next() % 2 == 0) DirectionY = -1; else DirectionY = 1;
}
public bool EdgeProcessing(Rectangle r)//边缘处理
{
bool b = false;
if (DirectionX == -1)//如果方向是向左
if (this.X - this.R <= r.X)//如果超出边界
{
DirectionX *= -1;//方向取反
b = true;
}
if (DirectionX == 1)//如果方向是向右
if (this.X + this.R >= r.X + r.Width)//如果超出边界
{
DirectionX *= -1;//方向取反
b = true;
}
if (DirectionY == -1)//如果方向是向上
if (this.Y - this.R <= r.Y)//如果超出边界
{ DirectionY *= -1;//方向取反
b = true;
}
if (DirectionY == 1)//如果方向是向下
if (this.Y + this.R >= r.Y + r.Height)//如果超出边界
{
DirectionY *= -1;//方向取反
b = true;
}
return b;
}
public bool IsContact(Ball b)
{
double distance;
distance = Math.Sqrt((this.X - b.X) * (this.X - b.X) + (this.Y - b.Y) * (this.Y - b.Y));
if (distance <= this.R+b.R )
return true;
else
return false;
}
public void Analysis(Ball b)//如果相碰改方向
{
if (IsContact(b))
{
this.DirectionX *= -1;
this.DirectionY *= -1;
b.DirectionX *= -1;
b.DirectionY *= -1;
}
}
}
}