简体   繁体   中英

How to delay with use of keyevent?

I want that when I press and hold space button that the spaceship's bullets shoot every 2 seconds. Now if I press and hold space button the spaceship shoots lots of bullets in one line. How can I fix this?

Method in class Game

public void newBullet() {                 
    Bullet k = new Bullet(this.spaceship.getX() + (Spaceship.WIDTH / 2), this.spaceship.getY() - 15, DEFAULT_SPEED,type.SPACESHIP);
    bullets.add(k);
}

public class ShootBullet extends TimerTask {
    private Game model;
    private SpaceInvadersController controller;
    
    public ShootBullet(Game model, SpaceInvadersController controller) {
        this.model = model;
        this.controller = controller;
    }

    @Override
    public void run() {
        long lastTime = System.nanoTime();             
        final double amountOfTicks = 60.0;
        final double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        while(true){
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1) {
                this.model.tick();
                Platform.runLater(controller::update);
                delta--;
            }
        }
    }
}

This is in controller:

private void move(KeyEvent k) {
    switch(k.getCode()){
        case LEFT:
            this.model.spaceshipLeft();
            break;
        case RIGHT:
            this.model.spaceshipRight();
            break;
        case UP:
            this.model.spaceshipUp();
            break;
        case DOWN:                     
            this.model.spaceshipDown();
            break;
        case SPACE:
            this.shoot();
            break;
    }
    view.update();      
}

private void shoot() {
    ShootBullet task = new ShootBullet(this.model, this);
    this.model.newBullet();
    timer2.scheduleAtFixedRate(task, 0, 1000);
    update();
}

Check the documentation for KeyEvent . You will notice there are three types of events:

  • KEY_PRESSED
  • KEY_TYPED (is only generated if a valid Unicode character could be generated.)
  • KEY_RELEASED

The KEY_TYPED events are the problematic ones for you, since they are generated by the hardware/keyboard driver according to operating system settings. You cannot change the rate at which they fire.

But you can completely ignore them and go for KEY_PRESSED and KEY_RELEASED. So as soon as you notice a KEY_PRESSED event, start your timer that will fire at the rate you want, and stop that timer when you receive a KEY_RELEASED.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM