Javascript 如何使用按键阻止形状移动?
如何使我的形状在每次按下空格键时停止,并在再次按下空格键时移动 要暂停并继续更新位置,您需要创建一个单独的变量来跟踪此状态更改:在这种情况下,布尔值是完美的 e、 g 您可以使用来侦听处理过程中的关键更改:Javascript 如何使用按键阻止形状移动?,javascript,java,processing,Javascript,Java,Processing,如何使我的形状在每次按下空格键时停止,并在再次按下空格键时移动 要暂停并继续更新位置,您需要创建一个单独的变量来跟踪此状态更改:在这种情况下,布尔值是完美的 e、 g 您可以使用来侦听处理过程中的关键更改: void draw(){ } void keyPressed(){ println("key: " + key + " keyCode: " + keyCode); } 下一部分是切换布尔值: 如果该值为true,则将其设置为false 如果为false,则将其设置为true e、
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)
shouldSquareUpdate = !shouldSquareUpdate;
}
最后,您将使用此条件确定是否应更新y
值:
完整的草图如下所示:
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;
}
请记住,720/8=90像素/帧,60帧/秒,即5400像素/秒:waaay to fast可使运动清晰可见
你可以使用同样的原理,以32个相等的步骤移动盒子?
e、 g
感谢您的帮助,您比我的讲师讲得更清楚了,但是您如何集成空格键,使其仅在我按下时停止和启动?我非常确定您能够使用
keyPressed()
函数来完成这项工作(如您上面所示)并检查按下的键是否为空格字符('
)(或者使用keyCode
,如果使用println(“键:“+key+”键代码:“+keyCode”);
示例并为右键代码值编写if
条件)。祝你好运,玩得开心调整/破坏/修复代码:)
void keyPressed(){
// toggle boolean (if true, set it to false, if false, set it to true)
shouldSquareUpdate = !shouldSquareUpdate;
}
// update only if value is true
if(shouldSquareUpdate){
y += dy;
}
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;
}
// in setup()
dy = height / 8;
void setup() {
size(1280, 720);
surface.setResizable(true);
// make square move in 32 equal steps: increment 32th of the total height
dy = height / 32;
}