Hi all I'm programming a 2D game (mario clone) and I have a little problem: is there a way to remove the fact that if I press the fire-button and i keep it pressed it start spawning milions of fireballs ?
Any help would be very appreciated, my thanks.
Edit: 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() == ObjectId.Player){
if(key == KeyEvent.VK_D) tempObject.setVelX(5);
if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
if(key == KeyEvent.VK_W && !tempObject.isJumping()) {
tempObject.setJumping(true);
tempObject.setVelY(-13);
}
if(key == KeyEvent.VK_SPACE){
int velocity = tempObject.getLookingLR() * 5;
float posX = tempObject.getX() + velocity;
float posY =tempObject.getY()+32;
handler.addObject(new Bullet(posX,posY, ObjectId.Bullet, velocity,handler));
tempObject.setFiring(true);
}
}
}
if(key == KeyEvent.VK_ESCAPE){
System.exit(1);
}
}
You almost have it. You don't actually check your player's object to see if it's firing:
if(key == KeyEvent.VK_SPACE){
int velocity = tempObject.getLookingLR() * 5;
float posX = tempObject.getX() + velocity;
float posY =tempObject.getY()+32;
handler.addObject(new Bullet(posX,posY, ObjectId.Bullet, velocity,handler));
tempObject.setFiring(true);
}
Should be:
if(key == KeyEvent.VK_SPACE && !tempObject.isFiring()){
int velocity = tempObject.getLookingLR() * 5;
float posX = tempObject.getX() + velocity;
float posY =tempObject.getY()+32;
handler.addObject(new Bullet(posX,posY, ObjectId.Bullet, velocity,handler));
tempObject.setFiring(true);
}
You also need to add a keyReleased
method that sets firing
to false
:
public void keyReleased(KeyEvent e) {
//your code for getting key event and finding the player Object
if(key == KeyEvent.VK_SPACE) {
//Do any necessary cleanup of the firing here
tempObject.setFiring(false);
}
}