[英]Making block/Character move “X px” when “W or w” is only once when pressed, and not continue walking when “W and w” is held down
当我按下“W 或 w”时,我想让我的 Rectangle/Character 移动“X px”,但只移动一次。 按住“W and w”时不要继续移动。 我尝试制作一个“Key Released” function,其变量在按下“W 或 w”时会发生变化。 但它并没有真正起作用,它只是让矩形/字符移动了“X px's”一次,然后就不会朝那个方向移动。 简而言之,我希望每次“单击”按钮时矩形/字符移动 50 像素,逐步进行。 而不是流畅的运动。 有谁能帮忙吗? 代码写在Java,处理中。
class Character {
float x = 0;
float y = 0;
//VV Movement VV
void move() {
if (keyPressed) {
if (key == 'w' || key == 'W') {
//terms, move forward/up, Y-axel.
y -= 50;
}
}
if (keyPressed) {
if (key == 'a' || key == 'A') {
//terms, move right, X-axel.
x -= 50;
}
}
if (keyPressed) {
if (key == 's' || key == 'S') {
//terms, move backwards/down, Y-axel.
y += 50;
}
}
if (keyPressed) {
if (key == 'd' || key == 'D') {
//terms, move left, X-axel.
x += 50;
}
}
}
我想让我的 Rectangle/Character 移动 [...] 但只有一次
添加一个keyPressed()
事件并从该事件中调用move
,但不要在draw()
中调用它。
注意keyPressed
每次按下一个键时都会调用一次。 所以当一个键被按下时,角色只移动一次。 但是由于操作系统可能会处理按键重复,因此必须存储最后按下的按键。 如果在keyReleased
发生之前再次按下相同的键,则必须跳过它。 例如:
Character ch = new Character();
int lastKey = 0;
void keyPressed() {
if (lastKey != key) {
lastKey = key;
ch.move();
}
}
void keyReleased() {
lastKey = 0;
}
在示例中ch
假定为您的Character
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.