处理时移动矩形?

时间:2015-02-21 15:23:02

标签: java animation processing

我有以下代码(我没有在此处编写设置和绘图),我想在Processing上移动一个矩形。如果按'a'则向左,如果按'd'则向右。 使用此代码,我执行此操作,但如果moveTo为低数字,则矩形移动得太​​慢,如果moveTo为高数字,则矩形移动得很快。它不流畅...... 我该怎么做这个动画?

int moveTo = 5;
void keyPressed()
{
  if (key == 'a')
  {
       xTopRect = xTopRect - moveTo;
       xBottomRect = xBottomRect - moveTo;
       xFstPointTriangle = xFstPointTriangle - moveTo;
       xSndPointTriangle = xSndPointTriangle - moveTo;
       xTrdPointTriangle = xTrdPointTriangle - moveTo;
  }
  else if (key == 'd')
  {
       xTopRect = xTopRect + moveTo;
       xBottomRect = xBottomRect + moveTo;
       xFstPointTriangle = xFstPointTriangle + moveTo;
       xSndPointTriangle = xSndPointTriangle + moveTo;
       xTrdPointTriangle = xTrdPointTriangle + moveTo;
   }  
}

我找到了这个解决方案并且它有效(不要看变量) 我在draw()

中调用move()
void move()
{
  if (keyPressed) {
    if (key == 'a') {
      x = x - speed;
    } else if (key == 'd') {
      x = x + speed;
    }
  }
}

2 个答案:

答案 0 :(得分:0)

int moveTo = 5;
int MAX_MOVE_TO=100;
int counter=0;
void keyPressed()
{

  counter++;
  if(counter==(MAX_MOVE_TO-moveTo))
  {
     if (key == 'a')
     {
           xTopRect = xTopRect - 1;
           xBottomRect = xBottomRect - 1;
           xFstPointTriangle = xFstPointTriangle - 1;
           xSndPointTriangle = xSndPointTriangle - 1;
           xTrdPointTriangle = xTrdPointTriangle - 1;
     }
     else if (key == 'd')
     {
           xTopRect = xTopRect + 1;
           xBottomRect = xBottomRect + 1;
           xFstPointTriangle = xFstPointTriangle + 1;
           xSndPointTriangle = xSndPointTriangle + 1;
           xTrdPointTriangle = xTrdPointTriangle + 1;
     }  
     counter=0;
  }
}

请尝试不同的moveTo值在0到99之间。它应该在所有速度下平稳移动。

您正在使用按键移动对象,但您可以在不同的线程中执行此操作,以便在您不按键时它也可以移动。

答案 1 :(得分:0)

目前,我认为您的代码正在使用KeyListener来触发移动。您可以做的一件事是创建并ArrayList<Integer>来保存已关闭的键的值。然后,在循环中,检查ArrayList的A和D键值,如果它们在其中则移动。

现在的问题是,KeyListener每次只会注册一个KeyEvent。使用此解决方案,您将能够控制矩形位置更新的频率。

ArrayList<Integer> keysDown = new ArrayList<Integer>();
void keyPressed(KeyEvent e) {
    if (!keysDown.contains(e.getKeyCode()) {
        keysDown.add(e.getKeyCode());
    }
}
void keyReleased(KeyEvent e) {
if (keysDown.contains(e.getKeyCode()) {
        keysDown.remove(e.getKeyCode());
    }
}

然后在您的更新或绘制循环中,

if (keysDown.contains(KeyEvent.VK_A)) {
    xTopRect = xTopRect - moveTo;
    xBottomRect = xBottomRect - moveTo;
    xFstPointTriangle = xFstPointTriangle - moveTo;
    xSndPointTriangle = xSndPointTriangle - moveTo;
    xTrdPointTriangle = xTrdPointTriangle - moveTo;
} else if (keysDown.contains(KeyEvent.VK_D)) {
   xTopRect = xTopRect + moveTo;
   xBottomRect = xBottomRect + moveTo;
   xFstPointTriangle = xFstPointTriangle + moveTo;
   xSndPointTriangle = xSndPointTriangle + moveTo;
   xTrdPointTriangle = xTrdPointTriangle + moveTo;
}