Why does my player move off the screen when I set

2019-09-10 03:58发布

问题:

for the past few days i have been tinkering around with moving the player with just one camera and having the camera follow the player's x and y. When i searched this up all i found was to move the player and set the camera's x and y to that. But i am having a problem, my player does not stay in the middle of the screen and it is really anoying. If anyone could hep me that would be great. Here is the code.

in the create;

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Main.WIDTH, Main.HEIGHT);

    batch = new SpriteBatch();
    batch.setProjectionMatrix(cam.combined);

in the update;

    cam.position.set(Player.getX() + Main.WIDTH / 2, Player.getY() + Main.HEIGHT / 2, 0);
    cam.update();

in the movement;

    if (Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)) {

        Player.setVelY(Player.SPEED);

    } else if (Gdx.input.isKeyPressed(Keys.S)
            || Gdx.input.isKeyPressed(Keys.DOWN)) {

        Player.setVelY(-Player.SPEED);

    } else {

        Player.setVelY(0);

    }

    if (Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)) {

        Player.setVelX(-Player.SPEED);
        Player.dir = Player.Direction.LEFT;

    } else if (Gdx.input.isKeyPressed(Keys.D)
            || Gdx.input.isKeyPressed(Keys.RIGHT)) {

        Player.setVelX(Player.SPEED);
        Player.dir = Player.Direction.RIGHT;

    } else {

        Player.setVelX(0);
        Player.dir = null;

    }

回答1:

I'd suggest you just set the camera position to the position of the Sprite of the player. I can't tell what your Player.getX() returns but it should probably return the x-coordinate of the Sprite denoting the player. The same goes for the y-coordinate.

cam.position.set(Player.getX() + Main.WIDTH / 2, Player.getY() + Main.HEIGHT / 2, 0);

would be

cam.position.set(Player.getX() + Player.getWidth() / 2, Player.getY() + Player.getHeight() / 2, 0);