简体   繁体   English

限制Java Swing游戏中的玩家移动“速度”

[英]Restrict Player Movement “Speed” in Java Swing Game

I've implemented a game where a player can move a sprite around in a tile-based maze. 我实现了一款游戏,玩家可以在基于图块的迷宫中移动精灵。 The player controls the sprite with the arrow keys. 播放器使用箭头键控制精灵。 What I want is to restrict the speed at which the player can move around, eg I don't want them to be able to hold down the arrow key and fly across the screen. 我要限制玩家的移动速度,例如,我不希望他们按住箭头键并在屏幕上飞来飞去。 I tried fixing this by implementing a sleep: 我尝试通过实施睡眠来解决此问题:

switch (keyCode) {
        case KeyEvent.VK_UP:    // Up arrow key
            if (running) {
                player.Move(1); // Move North
            }
            paintPlayer(getGraphics());
            // So the player can't hold down the arrow key and fly across the screen, force them to wait between inputs
            // BUT this leads to problems if you do hold it down, moves end up in a 'queue'...
            try {
                Thread.sleep(150);
                break;
            } catch (InterruptedException ex) {
                Logger.getLogger(MazeView.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
// etc.

But this leads to problems if you hold the arrow key down - the moves seem to end up in some kind of "queue" and you end up constantly crashing into a wall until all the moves from your extended key press are done. 但这会导致问题,如果您按住箭头键-这些动作似乎最终会陷入某种“排队”状态,并且您最终会不断崩溃,直到从扩展按键完成所有动作为止。 Is there a better way of doing this? 有更好的方法吗?

Previously I was doing a keyPressed() event, but as Riyafa suggested, I changed it to only fire on keyReleased(), and that's done it. 以前我在做keyPressed()事件,但是正如Riyafa建议的那样,我将其更改为仅在keyReleased()上触发,并且做到了。 There's no need to include sleeps anymore either. 也无需再包括睡眠。

I advise to investigate Switng Timer. 我建议调查Switng计时器。 As the name suggests its action is performed in the same thread as your Key event listener and all other GUI stuff, so you can easily painting there and update game state, based on key/button states. 顾名思义,它的动作与Key事件侦听器和所有其他GUI东西在同一线程中执行,因此您可以轻松地在此处绘画并基于键/按钮状态更新游戏状态。 You can also use swingutilities.invokelater(new runnable() if you are waiting is some another thread. I did not do Swing for a long time and forgotten everything but I am sure that this is how dynamic games are supposed to be done. 您也可以使用swingutilities.invokelater(new runnable()如果您正在等待另一个线程。我很长时间没有做Swing并忘记了所有事情,但是我敢肯定,这应该是动态游戏的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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