Search code examples
javaslick2d

Setting the max and min value for delta in slick2d


Though it looks funny in my game, I have some basic rts movement where you right click and the unit moves there. But sometimes when I run the game the unit moves much slower than normal but nothing has been changed in the code (other times the unit moves much faster). When I open up more programs the speed returns to normal but if i'm just running Netbeans I get super slow movement.

I have a feeling it has something to do with the delta value(not really sure) for updating but as i'm new to slick2d I don't know where to start with fixing the problem.

So my question is, can I limit the delta value so it can't update too slow or too fast and is delta even my problem?

http://pastebin.com/fRndGE2p //Main class

http://pastebin.com/KJ8W3134 //PlayerStats


Solution

  • I see now. You did not turned on the VSync.
    Note: The VSync limits your framerate to your monitors refresh rate (usually 60fps).
    Ohh and the maximum/minimum update intervals are in miliseconds.

    So the following example makes the game very laggy:

    app.setVSync(true);                     // Turn VSync
    app.setMaximumLogicUpdateInterval(200); // Max. 200 miliseconds can pass
    app.setMinimumLogicUpdateInterval(100); // Min. 100 miliseconds must pass
    

    So i think you have to play around the numbers to make it optimal.

    But, this is not what you need :D
    I saw this:

    player_X = player_X + velocityX;
    player_Y = player_Y + velocityY;
    

    So this was your code, to update the positions of the player. You must use the delta number.

     public void update(GameContainer gc, int delta)
    

    As you can see the delta is a pre defined integer. The delta contains the time that passed between two updates. So after this you should multiply everything with delta.

    Check this:

    player_X += velocityX * delta;
    player_Y += velocityY * delta;
    
    // The '+=' means player_X = player_X + something (if you did not know)
    

    Note: If the player moves slowly after the change, then simply multiply it with a number like this:

    player_X += velocityX * delta * 1.5f;
    player_Y += velocityY * delta * 1.5f;
    

    Example:

    The Runnable Jar
    MainComponent.java
    GameState.java

    This is a self made fast and simple example for you. Try it out, taste the source code:D
    Oh and this distance calculating method makes the player shaky.