如何在 J2ME 中使用 GameCanvas 来使用 keyPressed 事件?

发布于 2024-12-21 03:13:11 字数 1003 浏览 5 评论 0原文

好吧,我有一个无法解决的问题,并尝试了多种方法,但没有成功。我想按下一个按钮,如果它保持按下状态,子弹就无法发射。

所以我首先尝试了这个:

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;
    }
}

我在主循环中调用这个方法。这是可行的,但如果按键保持按下状态,子弹仍然会射出。当我尝试重写 keyPressed 方法时,它不起作用,因为我不知道如何调用此方法。如果我尝试直接在主循环中调用它,它就不起作用,那么,我怎样才能让它起作用呢?

任何人都可以告诉我如何调用此方法才能正常工作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一笑百媚生 2024-12-28 03:13:11

getKeyStates() 本身不报告事件。如果某个键被按住或者在当前调用 getKeyStates 和最后一次调用之间的某个时刻被按下,它将在该键上返回 true。您必须覆盖 keyReleased 方法,当用户松开按键而不是按下按键时执行操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文