private void timer1_Tick(object sender, EventArgs e)
{
int x = r.Next(0, pictureBox1.Width);
int y = r.Next(0, pictureBox1.Height);
button1.Top = y;
button1.Left = x;
}
private void button2_Click(object sender, EventArgs e)
{
}
编辑**
int x1 = r.Next(0, pictureBox1.Width);
int y1 = r.Next(0, pictureBox1.Height);
randomPoint = new Point(x1, y1);
if (currentPosition.X != randomPoint.X)
{
if (currentPosition.X > randomPoint.X)
currentPosition.X -= 1;
else
currentPosition.X += 1;
button1.Location = currentPosition;
}
else if (currentPosition.Y != randomPoint.Y)
{
if (currentPosition.Y > randomPoint.Y)
currentPosition.Y -= 1;
else
currentPosition.Y += 1;
button1.Location = currentPosition;
}
else
{
randomPoint.X = r.Next(0, pictureBox1.Width - button1.Width - 1);
randomPoint.Y = r.Next(0, pictureBox1.Height - button1.Height - 1);
}
在表格的顶部我做了:
int x ;
int y ;
Point currentPosition;
Point randomPoint;
在构造函数中:
x = button1.Location.X; y = button1.Location.Y; currentPosition = new Point(x,y);
答案 0 :(得分:1)
在表单加载事件中执行:
currentPosition = button1.Location;
randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);
在计时器内:
if(currentPosition.X != randomPoint.X){
if (currentPosition.X > randomPoint.X)
currentPosition.X -= 1;
else
currentPosition.X += 1;
Button1.Location = currentPosition;
}
else if(currentPosition.Y != randomPoint.Y){
if(currentPosition.Y > randomPoint.Y)
currentPosition.Y -= 1;
else
currentPosition.Y += 1;
Button1.Location = currentPosition;
}
else{
randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);
}
就移动而言,您可以增加picturebox
尺寸or(and)
dicrease button
大小。
不要忘记在Random r = new Random();
和currentPosition
声明randomPoint
。
瓦尔特