【问题标题】:Why does my player move off the screen when I set the libGDX camera's position to the players x and y?为什么当我将 libGDX 摄像机的位置设置为玩家 x 和 y 时,我的玩家会离开屏幕?
【发布时间】:2024-01-11 11:00:01
【问题描述】:

在过去的几天里,我一直在尝试只用一个摄像头移动玩家并让摄像头跟随玩家的 x 和 y。当我搜索这个时,我发现只是移动播放器并将相机的 x 和 y 设置为那个。但是我遇到了一个问题,我的播放器没有停留在屏幕中间,这真的很烦人。如果有人能帮助我,那就太好了。这是代码。

在创建中;

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

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

在更新中;

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

在运动中;

    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;

    }

【问题讨论】:

    标签: java camera libgdx game-physics


    【解决方案1】:

    我建议您将相机位置设置为玩家精灵的位置。我不知道您的Player.getX() 返回什么,但它可能应该返回表示玩家的 Sprite 的 x 坐标。 y 坐标也是如此。

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

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

    【讨论】:

      最近更新 更多