[英]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.