2011-02-01 62 views
2

我已经写了一个应用程序来移动窗体上的图像与PictureBox。但我的代码只能将其水平移动......我使用了一个Timer。在c中移动图像的问题#

我需要从初始点(如X0,Y0)水平移动图像到达一个精确的位置(例如(Xc,Y0)),然后垂直向上或向下移动它以达到(Xc,Ym),然后移动(Xf,Ym)水平回放。

我写了那移动图像部分水平达到(XC,Y0),但我不知道怎么写别人...

这里是我的代码,从(X0,Y0)移动到( 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); 

    } 
} 

另外,我已经做了一些尝试,但没有得到任何结果...

这里是我的尝试(尝试改变方法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(); 
      } 

     } 
    } 

请你们帮我完成这个...

+0

我会建议做一个新的变量* t *的时间,这将增加每个滴答。然后你会计算x和y,它可能会更清晰。 – Justin 2011-02-01 15:04:18

+0

@贾斯汀 - 你能解释一下吗?! – 2011-02-01 16:44:08

回答

1

的关键是使用时间,而不是X为你的关键:

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(); 
} 

,因为当你试图减小对Way X受回X0 ,你会回落到你的第一个if区块。