简体   繁体   English

你如何使用 LibGDX 实现水平滚动?

[英]How do you implement Horizontal-Scrolling with LibGDX?

I want to program a game that is like the old "Warfare 1917" browser games.我想编写一个类似于旧的“战争 1917”浏览器游戏的游戏。 I am stuck on the scrolling part.我被困在滚动部分。

I'll try to explain what I want to with a gif:我将尝试用 gif 解释我想要的内容:

在此处输入图片说明

I have searched and tried everything the whole day but I am not able to find any real solutions to this.我已经搜索并尝试了一整天,但我找不到任何真正的解决方案。 I hope you can understand what I am trying to do.我希望你能理解我想要做什么。

I think this should do the trick我认为这应该可以解决问题

public class MovingCamera extends InputAdapter {

    OrthographicCamera camera;    // The camera to be moved
    float pivotX;                 // The pivot for the movement

    public MovingCamera() {
        camera = new OrthographicCamera(); // Initialize camera
    }

    // Create a pivot
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
        pivotX = unprojected.x;                                                   // Save first finger touch on screen (Will serve as a pivot)
        return true;                                                              // Input has been processed
    }

    // Move the camera
    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
        camera.position.x += unprojected.x - pivotX;                              // Change camera position
        camera.update();                                                          // Apply changes
        return true;                                                              // Input has been processed
    }
}

And in your render method:在你的渲染方法中:

public void render(SpriteBatch spriteBatch) {
    spriteBatch.setProjectionMatrix(camera.combined); // Let the Sprite Batch use the camera
    spriteBatch.begin();
    // [Draw your Textures, TextureRegions, Sprites, etc...]
    spriteBatch.end();
}

Since moving camera is a bad practice, better moving a Layer (the container of your sprites) or you can try ScrollPane , the implementation of the WidgetGroup由于移动相机是一个不好的做法,最好移动一个图层(你的精灵的容器)或者你可以尝试ScrollPaneWidgetGroup的实现

See https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.htmlhttps://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.html

ps tested on v. 1.9.11 ps 在 v. 1.9.11 上测试

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

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