Reputation: 985
I’ve written an application to move an image on the form with PictureBox
. But my code only move it horizontally…I used one Timer.
I need to move the image horizontally from initial point (e.g. X0,Y0) to reach an exact location (e.g. (Xc,Y0) ) then move it vertically up or down to reach (Xc,Ym) and then move back it horizontally to reach (Xf,Ym).
I have written that part that move image horizontally to reach (Xc,Y0) but I don’t know how to write the others…
Here is my code that move from (X0,Y0) to (Xc,Y0):
public partial class Form1 : Form
{
void timer_Tick(object sender, EventArgs e)
{
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
pictureBox1.Location = new Point(x + 2, y);
if (x > 500)
timer1.Stop();
}
public Form1()
{
InitializeComponent();
pictureBox1.ImageLocation = "1.png";
pictureBox1.Size = new Size(36, 35);
timer1.Interval = 15;
timer1.Start();
timer1.Tick += new EventHandler(timer_Tick);
}
}
Besides, I have did some attempts but didn’t get any result…
Here is my attempts (try to change method timer_Tick ) :
void timer_Tick2(object sender, EventArgs e)
{
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
if (x <= 500)
pictureBox1.Location = new Point(x + 2, y);
if (x > 500)
{
if (y <= 250)
pictureBox1.Location = new Point(x, y + 1);
if (y == 250)
{
pictureBox1.Location = new Point(x - 2, y);
if (x < 50)
timer1.Stop();
}
}
}
Please guys help me to complete this...
Upvotes: 2
Views: 1052
Reputation: 10377
The key is to use time rather than x as your key:
int t = 0;
void timer_Tick1(object sender, EventArgs e)
{
t++;
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
if (t <= 250)//go right 500 in 250 ticks
pictureBox1.Location = new Point(x + 2, y);
else if (t <= 500)//...then go down 250 in 250 ticks
pictureBox1.Location = new Point(x, y + 1);
else if (t <= 750)//...then go left 500 in 250 ticks
pictureBox1.Location = new Point(x - 2, y);
else
timer1.Stop();
}
because when you attempt to decrement x on the way back to x0, you will fall back into your first if
block.
Upvotes: 1