Java上下移动图像,动画运动

时间:2012-05-21 13:55:29

标签: java image paint repaint

我想知道如何在绘制图像后移动图像?

这是我绘制图像的代码:

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 个答案:

答案 0 :(得分:1)

你需要有一个全局变量或某个地方的另一个变量,表明......

  1. 图片需要移动
  2. 已经移动了Y方向的距离
  3. 它的方向(向上或向下)
  4. 如果有此功能,则需要在paint()方法中添加代码,以便在正确的位置绘制图像。

    您还需要一个TimerThread,它会每隔几毫秒告诉组件repaint(),并更改您的全局变量,以便将其重新绘制得更低/更高。< / p>

    所以,作为一个例子,你可能有一些像这样的全局变量......

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

    这至少应该指向正确的方向。

相关问题