Search code examples
javamethodslwjgl

LWJGL method with keyboard input does not work in game loop


I'm trying to make a game in java and I'm using LWJGL. So I'm able to move a quad around the screen using arrow keys and it works very nicely. Although the code for that is in the Main constructor, which works but it doesn't look very nice. So I decided to put it in a method and call the method within the Main constructor to save some space in the constructor. However when I put the code in a method, and call it, the function doesn't work. The cube won't move when I press the arrow keys.

This is my move method(which doesn't do anything when called in the main constructor):

public static void moveSquare(float x, float y, float speed, int deltaTime){
    if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){
        x += speed * deltaTime;
    } 
    if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
        x -= speed * deltaTime;
    }
    if(Keyboard.isKeyDown(Keyboard.KEY_UP)){
        y -= speed * deltaTime;
    }
    if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
        y += speed * deltaTime;
    } 

Here is my Main constructor where the game loops is. Some instances that i have are float x, float y, float speed, int width, and int height. just in case you see them referenced in the code and wonder where they came from.

public Main(){
    Display.setTitle("Squares!");
    try {
        Display.setDisplayMode(new DisplayMode(800,600));
        Display.create();
    } catch (LWJGLException e) {
        e.printStackTrace();
    }

    initGL();

    while(!Display.isCloseRequested()){

        int deltaTime = getDelta();

        drawSquare(x, y, width, height);
        moveSquare(x, y, speed, deltaTime);

        initClock();
        Display.update();
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
        Display.sync(64); 
    } 

    Display.destroy();
}

Solution

  • A static method belongs to class, not to the objects. If you would like to access a non static field within your static method like x, y, speed... it would give you an error. But what you are actually doing here is passing a couple parameters to your move method which is doing a couple thing with them doesn't really matter what because that will only modify those copies within your method.

    Let's say you have a Square class and you want to make it move with a move method that should not be static

    public void move(float dt){
        //move stuff here
    }
    

    You don't even have to pass arguments only delta time because every square object will have its own copy(if not static) and move will use those.