2012-03-16 50 views
0

我正在嘗試做一個簡單的任務。我有一個從屏幕左上角開始的圓圈。當我觸摸屏幕上的任何地方時,我希望圓圈緩慢移動並停在用戶觸摸的位置。我已經成功實現了這一點,但圓圈移動速度太快。我相信我需要嘗試將我的run()線程休眠幾毫秒,但我似乎無法成功完成此操作。這將是什麼解決方案?代碼很簡單,但爲了以防萬一,我在下面貼出來,謝謝你提前的幫助!圖像移動太快,觸摸

Thread t = null; 
    SurfaceHolder holder; 
    boolean isItOK = false; 

    public GameView(Context context) 
    { 
     super(context); 
     // TODO Auto-generated constructor stub 
     holder = getHolder(); 
    } 

    public void run() 
    { 
     Display display = getWindowManager().getDefaultDisplay(); 
     int screenWidth = display.getWidth(); 
     int screenHeight = display.getHeight(); 
     int screenArrayWidth = screenWidth/50; 
     int screenArrayHeight = screenHeight/30; 
     int[][] mapArray = new int[50][30]; 

     while (isItOK) 
     { 
      if (!holder.getSurface().isValid()) 
      { 
       continue; 
      } 
      c = holder.lockCanvas(); 
      c.drawARGB(255, 255, 0, 0); 



      c.drawBitmap(ball, destinationX - (ball.getWidth()/2), 
        destinationY - (ball.getHeight()/2), null); 


     } 
    } 


public boolean onTouch(View v, MotionEvent me) 
{ 
    switch (me.getAction()) 
    { 
    case MotionEvent.ACTION_DOWN: 
    { 
     while (((int)(me.getX()) != (int)(destinationX)) && ((int)(me.getY()) != (int)(destinationY))) 
     { 
      if (me.getX() > destinationX) 
      { 
       destinationX++; 

      } 

      if (me.getX() < destinationX) 
      { 
       destinationX--; 

      } 

      if (me.getY() > destinationY) 
      { 
       destinationY++; 

      } 

      if (me.getY() < destinationY) 
      { 
       destinationY--; 

      } 

     } 
    } 
+0

將Thread.sleep()添加到運行循環沒有幫助?在每個位圖繪製它從代碼片段中轉義出來之後,你會解鎖並釋放它,對嗎? – 2012-03-16 17:30:25

+0

是的,我在幾個時間間隔嘗試了Thread.sleep(),但這似乎沒有任何效果。是的,我有unlockAndPost()方法,但是在意外情況下我將它遺漏了。 – Derek 2012-03-16 17:36:41

回答

0

好的,你遇到的問題是,你沒有考慮經過的時間。這也意味着動畫將以不同的速度在不同的設備上移動,並且不同的東西在後臺運行。你需要做的是確定每毫秒有多少像素需要圓形移動,然後根據自最後一幀起經過的時間修改移動距離。

+0

Linear Interpolator也可能有所幫助。 – triggs 2012-03-16 17:39:17