Search code examples
javalibgdx

Code efficiency with LibGDX Box2D Player Movement


I am using Box2D in LibGDX to move my player around. The world gravity is set on (0f,0f). However, my code feels long and blunt and I feel like I could refactor it to implement it more efficient, but I'm not sure how. Is there anything I can improve?

private void playerMovement() {
    if(Gdx.input.isKeyPressed(Input.Keys.W)){
        body.setLinearVelocity(new Vector2(0f,30f));
    }if(Gdx.input.isKeyPressed(Input.Keys.S)){
        body.setLinearVelocity(new Vector2(0f, -30f));
    }if(Gdx.input.isKeyPressed(Input.Keys.A)){
        body.setLinearVelocity(new Vector2(-30f, 0f));
    }if(Gdx.input.isKeyPressed(Input.Keys.D)){
        body.setLinearVelocity(new Vector2(30f,0f));
    }if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.A)){
        body.setLinearVelocity(new Vector2(-30f, 30f));
    }if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.D)){
        body.setLinearVelocity(new Vector2(30f, 30f));
    }if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.A)){
        body.setLinearVelocity(new Vector2(-30f, -30f));
    }if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.D)){
        body.setLinearVelocity(new Vector2(30f, -30f));
    }else if(!Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)){
        body.setLinearVelocity(new Vector2(0f,0f));
    }
}

Is this method good for smooth movement using Box2D? The world gravity is set on (0f,0f). Not sure if i can do it writing less code.


Solution

  • More efficient way.

    static float speed = 30; // move speed outside method to not create it each frame.
    
    private void playerMovement() {
        if(Gdx.input.isKeyPressed(Input.Keys.W)){
            body.setLinearVelocity(0f, speed); // removed Vector2(), it's not a good idea to cteate it each frame.
        }if(Gdx.input.isKeyPressed(Input.Keys.S)){
            body.setLinearVelocity(0f, -speed);
        }if(Gdx.input.isKeyPressed(Input.Keys.A)){
            body.setLinearVelocity(-speed, 0f);
        }if(Gdx.input.isKeyPressed(Input.Keys.D)){
            body.setLinearVelocity(speed,0f);
        }if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.A)){
            body.setLinearVelocity(-speed, speed);
        }if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.D)){
            body.setLinearVelocity(speed, speed);
        }if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.A)){
            body.setLinearVelocity(-speed, -speed);
        }if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.D)){
            body.setLinearVelocity(speed, -speed);
        }else {
            body.setLinearVelocity(0f,0f);
        }
    }