我如何通过按键阻止形状移动?

问题描述 投票:1回答:1

每次按下空格键时如何停止形状,再次按下空格键时如何移动形状。

javascript java processing
1个回答
1
投票

要暂停并继续更新位置,您需要创建一个单独的变量来跟踪此状态变化:在这种情况下,布尔值是完美的。

例如

boolean shouldSquareUpdate = true;

您可以使用keyPressed()来监听处理中的关键更改:

keyPressed()

下一部分是切换布尔值:

  • 如果值为void draw(){ } void keyPressed(){ println("key: " + key + " keyCode: " + keyCode); } ,则将其设置为true
  • 如果是false,请将其设置为false

例如

true

这可以用void keyPressed(){ // toggle boolean (if true, set it to false, if false, set it to true) if(shouldSquareUpdate == true){ shouldSquareUpdate = false; }else{ shouldSquareUpdate = true; } } 更好地解决,它实际上翻转了布尔值的状态:

logical NOT operator

最后,您将使用此条件来确定是否应更新void keyPressed(){ // toggle boolean (if true, set it to false, if false, set it to true) shouldSquareUpdate = !shouldSquareUpdate; } 值:

y

完整的草图是这样的:

// update only if value is true
  if(shouldSquareUpdate){
    y += dy;
  }

关于

我如何使我的方块以8个相等的步幅移动?

应该简单地将当前设置为1(每帧像素)的int x = 0; int y = 0; int dy = 1; boolean shouldSquareUpdate = true; void setup() { size(1280, 720); surface.setResizable(true); } void draw() { background(240, 240, 240); fill(255, 147, 79); rect(x, y, 90, 90); // update only if value is true if(shouldSquareUpdate){ y += dy; } if(y + 90 > height || y < 0) { dy *= -1; } } void keyPressed(){ // toggle boolean (if true, set it to false, if false, set it to true) shouldSquareUpdate = !shouldSquareUpdate; } 值更新为总移动距离(高度)的八分之一:

例如

dy

请记住,720/8 =每帧90像素,每秒60帧,即每秒5400像素:清晰的动作快得清晰。

您可以使用相同的原理以32个相等的步长移动盒子?例如

// in setup()
dy = height / 8;
© www.soinside.com 2019 - 2024. All rights reserved.