簡體   English   中英

Java上下移動圖像,動畫運動

[英]Java moving a image up and down, animated motion

我想知道在繪制圖像后如何移動圖像?

這是我繪制圖像的代碼:

public int probeX = 500;
public int Minerals = 400;
public int drawProbeA, drawProbe = 0;

public void init() {
   // Images Call
   probe = getImage(getDocumentBase(), "image/probe.png");
}

public void paint(Graphics g) {
   if (drawProbe == 1) {
      for (int k = 0; k < drawProbeA; k++) {

         g.drawImage(probe, probeX, 474, 50, 50, this);
         probeX += 50;
      }
      probeX = 500;
   }
}

public boolean mouseDown(Event e, int x, int y) {
   // Clicking on the probe icon
   if (x > 1068 && x < 1119 && y > 785 && y < 832 && onNexus == 1
         && Minerals >= 50) {
      drawProbeA += 1;
      drawProbe = 1;
      Minerals -= 50;
   }

   return true;
}

我該如何做,以便在繪制圖像后點擊圖標會導致圖像自動沿y軸向下移動(例如50像素)? 基本上,就像通過動畫將圖像向下滑動一樣? 然后停下來,然后移回原始位置。

我正在使用Applet,並且希望動畫反復循環播放。 謝謝。

您需要有一個全局變量或某個地方的另一個變量,該變量指示...

  1. 圖片需要移動
  2. 它已經在Y方向移動了多遠
  3. 它往哪個方向(向上或向下)

遇到這種情況時,需要將代碼添加到paint()方法中,以在正確的位置繪制圖像。

您還需要一個TimerThread ,它會告訴組件每隔幾毫秒repaint()一次,並更改全局變量,以便將其較低/較高地進行重新繪制。

因此,舉個例子,您可能會有一些這樣的全局變量...

int yPosition = 0;
boolean goingDown = true;

當您需要開始動畫時,啟動一個Timer ,反復調用以下內容...

if (goingDown == true){
    // if we've gone down 50 pixels, start going up again
    if (yPosition <= 0){
        goingDown = false;
        yPosition++;
    }
    else {
        yPosition--; // move it down 1 pixel
    }
}
else {
    // if we're going up and we reach 0, go down again
    if (yPosition >= 50){
        goingDown = true;
        yPosition--;
    }
    else {
        yPosition++; // move it up1 pixel
    }
}

component.repaint(); // this will call the paint() method

並非您的繪畫方法只需要在其他位置繪制圖像。 只需更改g.drawImage(probe,probeX,474,50,50,this); 喜歡包括yPosition ...

g.drawImage(probe,probeX,474+yPosition,50,50,this);

這至少應該為您指明正確的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM