简体   繁体   English

如何在循环中调用keyPressed()方法?

[英]How to call keyPressed() method in a loop?

How can I call the method keyPressed(KeyListener evt) in a loop? 如何在循环中调用方法keyPressed(KeyListener evt)? I want to programm a simple 2D java game, and here is my code of the keyPressed method: 我想编写一个简单的2D java游戏,这是我的keyPressed方法的代码:

private void KeyPressed(java.awt.event.KeyEvent evt) {

    key = evt.getKeyCode();

        if (key == KeyEvent.VK_W) {

            direction = 1;

            PlayerMovement();
        }
        if (key == KeyEvent.VK_S) {

            direction = 2;

            PlayerMovement();
        }
        if (key == KeyEvent.VK_D) {

            direction = 3;
        }
}
public class GameLoop implements Runnable {
    public void run() {
        //initialization goes here
        while(running){
            processInput();
            update();
            render();
        }
    } 
    processUpdate() {
         //here you listen to inputs
    }
}

You can set a couple booleans to track the keys are currently pressed down. 您可以设置几个布尔值来跟踪当前按下的键。 For example set movingRight = true; 例如,设置movingRight = true; if D is pressed and set movingRight = false; 如果按下D并设置movingRight = false; if D is released. 如果D被释放。 In update you update your positions according to keys are currently pressed. 在更新中,您可以根据当前按下的键更新您的位置。

However a game loop should cointain a lot more. 然而,游戏循环应该更多地融合。 This is just a very basic model. 这只是一个非常基本的模型。

About game loops: http://gameprogrammingpatterns.com/game-loop.html 关于游戏循环: http//gameprogrammingpatterns.com/game-loop.html

i told you have to use THREADS because here you are using the program but if you start a thread you can do what ever you want the program still works fine learn about thread because game are all about threads 我告诉你必须使用THREADS,因为在这里你正在使用该程序,但如果你开始一个线程,你可以做任何你想要的程序仍然可以正常学习线程,因为游戏都是关于线程

private class Walk_thread extends java.lang.Thread{

public void run(){
//call the walk methode here
PlayerMovement();
}
}

so when the key is pressed create a thread that call playermovement 因此,当按下该键时,创建一个调用playermovement的线程

if (key == KeyEvent.VK_W) {

        direction = 1;
new Walk_thread().start();//here the method run is called 
System.out.println("program will not stop the thread is walking and the program is continued too");
    }

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

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