我有這個圖片框稱爲obstaclePicture,當我的計時器(obstacleTimer)打勾時,我想移動到新的隨機X和Y位置。當計時器打勾時,將圖片框移動到隨機的X和Y
移動它的一點是它是我製作的遊戲中的一個障礙。
表格的1025; 545px大。
我有這個圖片框稱爲obstaclePicture,當我的計時器(obstacleTimer)打勾時,我想移動到新的隨機X和Y位置。當計時器打勾時,將圖片框移動到隨機的X和Y
移動它的一點是它是我製作的遊戲中的一個障礙。
表格的1025; 545px大。
假設你的PictureBox具有100x100像素尺寸。 timer1應該啓用
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Random r = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
int x = r.Next(0,925);
int y = r.Next(0,445);
pictureBox1.Top = y;
pictureBox1.Left = x;
}
}
}
嘗試這樣:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
tm.Interval = 100;
tm.Tick += new EventHandler(tm_Tick);
tm.Start();
}
Timer tm = new Timer();
void tm_Tick(object sender, EventArgs e)
{
pictureBox1.Location = new Point((int)(new Random().Next(0, 1025)), (int)(new Random().Next(0, 545)));
}
}
編輯:您還必須檢查你的圖片是境內或境外的形式:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
tm.Interval = 1000;
tm.Tick += new EventHandler(tm_Tick);
tm.Start();
}
Timer tm = new Timer();
int X = 0;
int Y = 0;
void tm_Tick(object sender, EventArgs e)
{
X = ((int)(new Random().Next(0, 1025)));
Y = ((int)(new Random().Next(0, 545)));
if (X > 1025 - pictureBox1.Width)
{
X = 1025 - pictureBox1.Width;
}
if (Y > 545 - pictureBox1.Height)
{
Y = 545 - pictureBox1.Height;
}
pictureBox1.Location = new Point(X, Y);
}
}
@HugoLöwgren:看我的編輯 – KF2 2013-04-06 15:49:37
謝謝:)工作得很好 – 2013-04-06 15:56:11