简体   繁体   中英

How I use keyPressed event using GameCanvas in J2ME?

Well, I have a problem that I can't solve and tried it in many ways, but, with no success. I want to press a button and if it stay down, the bullet can't fire.

So I tried this, first:

public void checkInput() {
    int iKeyPressed;

    iKeyPressed = this.getKeyStates();

    if((iKeyPressed & LEFT_PRESSED) != 0) {
        this.player.moveLeft();
    }
    else if((iKeyPressed & RIGHT_PRESSED) != 0) {
        this.player.moveRight();
    }

    if((iKeyPressed & FIRE_PRESSED) != 0 && this.bKeyReleased) {
        Bullet bullet;
        int x;
        int y;

        bullet = new Bullet(loadImage("bullet.png"), 4, 22, 1, (this.player.getVel()*2)*(-1));
        x = (this.player.getX()+(this.player.getWidth()/2))-(bullet.getWidth()/2);
        y = this.player.getY();
        bullet.setPosition(x, y);
        this.lstBullets.addElement(bullet);
        //this.bKeyReleased = false;
    }
}

And I call this method in my main loop. This works, but if the key stay down, the bullets still coming out. When I try to override the keyPressed method, it doesn't work, because I don't know how to call this method. If I try to call it directly in my main loop it doesn't work, so, how could I can make it works?

Anyone can show me how I call this method to works correctly?

getKeyStates() doesn't report events per se. It will return true on a key if it is held down OR was down at some point between the current call to getKeyStates and the last call to it. You will have to override the keyReleased method to take action when the user lets the key up instead of when they push it down.

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