2012-03-23 41 views
1

我試圖在對象保持動畫時點擊鼠標移動對象。有此網站上幾個類似的帖子,我已經根據我的代碼斷這樣的回答:使用鼠標在兩點間移動

An efficient algorithm to move ostrichs along a line at a constant speed

但我想使用一個線程保持動畫的對象。我應該怎麼做?這裏是我的代碼:

public void movePlayer(Graphics g, int finalX, int finalY) 
{ 
    int length = finalX - xpos; 
    int height = finalY - ypos; 

    int oldXpos = xpos; 
    int oldYpos = ypos; 

    double speed = 20; 
    double distanceX = (length)/speed; 
    double distanceY = (height)/speed; 

    double distance = (Math.hypot(length,height)); 
    double distanceTraveled = 0; 

    //This currently doesn't work: 
    move = new Thread(this); 
    { 
     while (distanceTraveled<distance) 
     { 
      //move the object by increments 
      xpos += distanceX; 
      ypos += distanceY; 
      distanceTraveled = Math.hypot(xpos-oldXpos, ypos - oldYpos); 
      drawPlayer(img, g); 
      for(int x = 0; x < 100000; x ++); 

     } 
    } 
} 
+0

你的問題在必要的細節上似乎很短,例如你的意思是「保持對象動畫」,這是Swing嗎? AWT?別的東西?請告訴我們所有我們需要知道的能夠幫助你。 – 2012-03-23 20:13:52

+0

我正在使用JApplet。我希望看到物體在兩點之間無縫移動。我將使用動畫精靈,但現在,我只有一張我正在使用的圖片。 – helsont 2012-03-23 20:22:00

回答

1

如果這是Swing,爲什麼不簡單地使用MouseListener來幫助您拖動該對象?如果要與鼠標分開設置動畫,請不要使用while(true)循環,除非要凍結事件線程。改用Swing Timer。如果這不是Swing,請告訴我們更多細節(拍攝,無論如何都要這樣做)!

+0

對於這個類,我使用AWT。但是對於我的applet,我正在使用JApplet。 – helsont 2012-03-23 20:27:14

+0

謝謝,我得到它與搖擺計時器一起工作。我會發布我的代碼,但我顯然需要7個小時。 – helsont 2012-03-23 20:46:43

+1

@ user1264811:我很高興您能夠使用Swing Timer。另外,我建議你不要將AWT與Swing組件混合使用。單獨使用Swing。 – 2012-03-23 21:31:47