使用键移动对象的方向并在 x 时间段内保持反转

Moving object's direction and keeping it reversed for x period of time using keys

在我对 Arduino 及其传感器提出疑问之前,为了更容易理解我的问题,我创建了一个使用按键的示例。

所以这个想法是针对我的 Arduino 项目的,我有一个激活的传感器,当它激活时,我想要一个桨在一个方向上移动,可以说持续几秒钟。在我的 arduino 项目中,我将 运行 一个 if 语句,如果该 if 语句不再为真,即使四秒移动尚未完成,对象也将停止执行该命令。

代替 Arduino 传感器,让我们通过按键来简化这一过程。当按下键时,我希望球向 方向移动四秒钟。我需要一种方法来说明如果按键被激活,即使它结束继续移动。我知道我可能需要使用布尔值和计时器来执行此操作,但我不确定如何使用。 (注意:重要的是我不想要按键或鼠标之类的东西我想要按键,因为它更像我正在使用的传感器)

这是一个示例代码(我没有以任何方式使用此代码,但我认为它对帮助我解决我想弄清楚的问题的人很有帮助):

int ballX;
int ballY;
int radius;
int ballSpeed;

void setup()
{
 size(600, 600);
 background(255, 255, 255);
 smooth();
 frameRate(60);

 ballX = width/2;
 ballY = height/2;
 radius = 15;
 ballSpeed = 8;

}

void draw()
{
  fill(255, 255, 255, 50);
  noStroke();
  rect(0, 0, width, height);

  fill(255, 0, 0);
  ellipse(ballX, ballY, radius*2, radius*2); 
}


void keyPressed()
{
  if ( (keyCode == LEFT) && (ballX > radius) )
  {
    ballX = ballX - ballSpeed;
  }

}

为此,您可能需要一个或多个单独的变量。类似于:

boolean moving = false; // is the ball moving
int moveUntilTime = -1; // time when it should stop

void draw()
{
  fill(255, 255, 255, 50);
  noStroke();
  rect(0, 0, width, height);

  fill(255, 0, 0);
  ellipse(ballX, ballY, radius*2, radius*2); 

  if (moving == true) {
     if (millis() < moveUntilTime) {
       ballX = ballX - ballSpeed;
     }
     else {
       moving = false;
     }
  }
}

void keyPressed()
{
  if ( (keyCode == LEFT) && (ballX > radius) )
  {
    moving = true;
    moveUntilTime = millis() + 5000; // move for 5 seconds
  }
}