Why does my player move off the screen when I set the libGDX camera's position to the players x and y?

你离开我真会死。 提交于 2019-12-12 04:53:35

问题


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);



来源:https://stackoverflow.com/questions/27196389/why-does-my-player-move-off-the-screen-when-i-set-the-libgdx-cameras-position-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!