I am using Slick2d to create a top-down game, however an rectangle than I am drawing to the display is moving faster to the left than to the right, and faster up than down.

I am updating frames like so:

public void update(GameContainer gameContainer, int delta) throws SlickException { 
    player = new Rectangle(playerX, playerY, 10, 20);

    if (gameContainer.getInput().isKeyDown(Input.KEY_LEFT)) {
        x -= delta * 0.1f;
    if (gameContainer.getInput().isKeyDown(Input.KEY_RIGHT)) {
        x += delta * 0.1f;
    if (gameContainer.getInput().isKeyDown(Input.KEY_UP)) {
        y -= delta * 0.1f;
    if (gameContainer.getInput().isKeyDown(Input.KEY_DOWN)) {
        y += delta * 0.1f;

I then simply draw the rectangle to the display. It is noteworthy that the rectangle class is aorg.newdawn.slick.geom.Rectangle.

Why are the speeds for the movement different, and how can I fix this?

EDIT: I have fixed the problem by slowing the movement to the left and up, but this does not explain why the problem occurs

  • \$\begingroup\$ The code seems to be fine. You can put debug statements inside each if block to check just in case any value is not getting set properly. \$\endgroup\$ – Hash Buoy Aug 22 '15 at 21:33

This is most likely a rounding error. I'm guessing that x and y are ints.

Keeping track of the x and y values as floats, I expect will fix the issue.

Consider if the values are being floored:

Moving Left 10 - 1.6 = 8

Moving Right 10 + 1.6 = 11

| improve this answer | |
  • 1
    \$\begingroup\$ Don't ints round towards 0? I ran this code System.out.println((int) -1.7); on my machine and it printed -1. But still, he shouldn't be storing coordinates as ints. \$\endgroup\$ – Kyranstar Aug 25 '15 at 2:12
  • \$\begingroup\$ Yes, they will but screen coords are never negative.. so bad example on my part. Try 5-1.6 = 3, not 4 \$\endgroup\$ – Fuzzy Logic Aug 25 '15 at 2:29
  • \$\begingroup\$ Oh, good point. \$\endgroup\$ – Kyranstar Aug 25 '15 at 2:29
  • 1
    \$\begingroup\$ Keep in mind, they do not "round toward 0," they truncate. This distinction is important. For instance, 1.9999 truncates to 1 and 2.0001 truncates to 2. That's where this unexpected behavior is most likely occurring, in the truncation. \$\endgroup\$ – BennyMathison Sep 8 '15 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.