I am trying to make a game at the moment and I am having trouble finding out how to make the player go faster by pressing shift at the same time.
Here's some of my code:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
for(int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if(tempObject.getId() == ID.Player) {
//key events for player 1
if(key == KeyEvent.VK_W) tempObject.setVelY(-5);
if(key == KeyEvent.VK_S) tempObject.setVelY(5);
if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
if(key == KeyEvent.VK_D) tempObject.setVelX(5);
if(key == KeyEvent.VK_W && key == KeyEvent.VK_SHIFT) tempObject.setVelY(-8);
if(key == KeyEvent.VK_S && key == KeyEvent.VK_SHIFT) tempObject.setVelY(8);
if(key == KeyEvent.VK_A && key == KeyEvent.VK_SHIFT) tempObject.setVelX(-8);
if(key == KeyEvent.VK_D && key == KeyEvent.VK_SHIFT) tempObject.setVelX(8);
}
}
if(key == KeyEvent.VK_ESCAPE) System.exit(1);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
for(int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if(tempObject.getId() == ID.Player) {
if(key == KeyEvent.VK_W) tempObject.setVelY(-0);
if(key == KeyEvent.VK_S) tempObject.setVelY(0);
if(key == KeyEvent.VK_A) tempObject.setVelX(-0);
if(key == KeyEvent.VK_D) tempObject.setVelX(0);
if(key == KeyEvent.VK_W && key == KeyEvent.VK_SHIFT) tempObject.setVelY(-0);
if(key == KeyEvent.VK_S && key == KeyEvent.VK_SHIFT) tempObject.setVelY(0);
if(key == KeyEvent.VK_A && key == KeyEvent.VK_SHIFT) tempObject.setVelX(-0);
if(key == KeyEvent.VK_D && key == KeyEvent.VK_SHIFT) tempObject.setVelX(0);
}
}
}
Now all this works but doesn't change the velX
to 7 to 5.
Two keys cannot actually be pressed at the same time. The keyPressed() method is actually being called twice (once for a letter button, and once for shift). To check whether or not shift is pressed, set a global boolean value to the state of the shift press and manage the variable's state with keyPressed and keyReleased. For example:
public boolean shiftPressed;
public void keyPressed(KeyEvent e) {
if(shiftPressed && e.getKeyCode() == VK_(a letter)) {
//Execute some code
}
else if(e.getKeyCode() == VK_SHIFT) {
shiftPressed = true;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == VK_SHIFT) {
shiftPressed = false;
}
}