简体   繁体   中英

How do I prevent my camera from being delayed in LibGDX?

I'm trying to make a movement system in LibGDX where everything moves at 5 pixel increments, to make it look more pixel-y I guess. I'm currently moving the player 5 pixels at a time, and then moving the camera to match the players position to keep him on screen at all times. This is the code I'm using to do that (runs every time render is called):

Vector2 newCoordinates = MovementUtilities.getIncremented(x, y);
    cam.position.set(newCoordinates.x, newCoordinates.y, 0);
    batch.draw(texture, cam.position.x-15, cam.position.y, width, height);

Code for MovementUtilities.getIncremented():

public static final int INCREMENT = 5;

public static Vector2 getIncremented(int x, int y) {
    return new Vector2(x-(x % INCREMENT), y-(y % INCREMENT));
}

However, when I try to run it, this happens: https://youtu.be/C_r0mOaxJgU The player seems to vibrate, as if the camera can't keep up with him or something.

Does anyone know what is happening? Am I missing something?

You could try something like this, let me know how it works for you.

    // initialize with your beginning position if you'd like.
private float x, y;
// initialize with your beginning position if you'd like.
private final Vector2 coordinates = new Vector2(x, y);

private final float moveSpeed = 5.0f;

public void function() {
    getNewPosition();
    cam.position.set(coordinates.x, coordinates.y, 0.0f);
    cam.update();

    // draw
}

public void getNewPosition() {
    coordinates.set(x - moveSpeed, y - moveSpeed);
}

You may also try removing the -15 part from the cam position X and see what that does.

You are updating the internal position of the camera, but without telling the camera to update the view matrix, which i guess must be happening irregularly elsewhere so not visually in sync. If you change camera parameters, update the view matrix (how the view is transformed to the screen).

Put this after your setPosition

cam.update();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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