简体   繁体   English

将libGDX摄像机的位置设置为播放器x和y时,为什么播放器会移出屏幕?

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

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. 在过去的几天中,我一直在尝试着只移动一个摄像机移动播放器,并使摄像机跟随播放器的x和y进行调整。 When i searched this up all i found was to move the player and set the camera's x and y to that. 当我进行搜索时,我发现的是移动播放器并将相机的x和y设置为该值。 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;

    }

I'd suggest you just set the camera position to the position of the Sprite of the player. 我建议您将摄像机位置设置为播放器Sprite的位置。 I can't tell what your Player.getX() returns but it should probably return the x-coordinate of the Sprite denoting the player. 我不知道您的Player.getX()返回什么,但是它可能应该返回Sprite表示玩家的x坐标。 The same goes for the y-coordinate. y坐标也是如此。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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