2011-02-01 45 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區塊。