我想让我的玩家跳跃,但是目前在按空格时玩家会无休止地跳跃。我希望能够使用空格键一次。我认为这与我经常勾选的getInput()方法有关,我试过暂停线程,但这对我没用。
这是KeyManager:
package com.zetcode;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyManager implements KeyListener{
private boolean[] keys;
public boolean up, down, left, right;
public boolean jump;
public float jumpingTime = 200;
public KeyManager(){
keys = new boolean[256];
}
public void tick(){
down = keys[KeyEvent.VK_S] ;
left = keys[KeyEvent.VK_A];
right = keys[KeyEvent.VK_D];
jump = keys[KeyEvent.VK_SPACE];
}
@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
System.out.println("A Key was pressed");
if(e.getKeyCode() == KeyEvent.VK_SPACE){
}
}
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
@Override
public void keyTyped(KeyEvent e) {
}
}
这是我的玩家类:
package com.zetcode;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
public class Player extends Creature {
private Creature creature;
public Player(Handler handler, float x, float y) {
super(handler, x, y, Creature.PLAYER_WIDTH, Creature.PLAYER_HEIGHT);
bounds.x = 16;
bounds.y = 31;
bounds.width = 40;
bounds.height = 58;
}
@Override
public void tick() {
getInput();
move();
handler.getGameCamera().centerOnEntity(this);
}
private void getInput(){
xMove = 0;
yMove = 3;
gravity = 2;
if(handler.getKeyManager().jump)
yMove = -speed + -5;
if(handler.getKeyManager().down)
yMove = speed;
if(handler.getKeyManager().left)
xMove = -speed;
if(handler.getKeyManager().right)
xMove = speed;
}
@Override
public void render(Graphics g) {
g.drawImage(Assets.player, (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);
//g.setColor(Color.RED);
//g.fillRect((int) (x + bounds.x - handler.getGameCamera().getxOffset()),
// (int) (y + bounds.y - handler.getGameCamera().getyOffset()),
// bounds.width, bounds.height);
}
}
答案 0 :(得分:0)
向你的Creature类添加一个布尔标志isJumping。然后将其添加到getInput方法:
if (!isJumping && handler.getKeyManager().jump)
{
//...apply your transformations for jumping
isJumping = true;
}
这可以防止每次按键跳转。但是现在变得更加棘手:这将(在你当前的代码中)仅触发一次跳跃,因为游戏不知道,当你的角色降落在地面上时。所以你需要在你的生物和地面之间进行碰撞检测。
在网上有一些关于碰撞检测的好文章,如果你使用物理引擎,通常已经包含了碰撞。
假设你已经实现了一个被调用的方法,一旦你的生物到达地面,你就可以添加:
public void creatureHitGround()
{
//...other stuff on hit ground
isJumping=false;
}
你重置了isJumping标志,它允许你触发一个新的跳跃。
结果:你多次按键,但只有在你回到地面时才跳。