LibGDX: moving the camera using Touch

I am creating an a2D Android game LibGDXand I use a spelling camera to move around the world.

To move the camera, the player must touch and drag the screen. Therefore, if you touch the screen and drag it to the right, the camera should move to the left. Thus, it should be similar to moving part of an enlarged image in a gallery. I hope you follow me.

This is the code:

public class CameraTestMain extends ApplicationAdapter {

    SpriteBatch batch;
    Texture img;
    OrthographicCamera camera;

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        camera = new OrthographicCamera(1280, 720);
        camera.update();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        handleInput();
        camera.update();

        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(img, 0, 0);
        batch.end();
    }

    public void handleInput() {

        // That is my problem

    }

}

I do not know what to write in the method handleInput(). I know there is an interface called InputProcessorwith a method touchDragged(int x, int y, int pointer)where you can handle Touch Drag, but I have no idea how to use it.

Thanks for your ideas and your help.

+4
2

InputProcessor - , , , - (, ).

, :

    public class CameraTestMain extends ApplicationAdapter implements InputProcessor

create() InputProcessor, :

    //create() method
    Gdx.input.setInputProcessor(this);

- touchDragged. , x y , , , touchDown. , , , .

    //touchDragged method
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        camera.position.set(camera.position.x + screenX, camera.position.y + screenY);

camera.update() render()!

,

+1

, , , , ,

Gdx.input.getDeltaX() X.

Gdx.input.getDeltaY() Y.

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    float x = Gdx.input.getDeltaX();
    float y = Gdx.input.getDeltaY();

    camera.translate(-x,y);
    return true;
}
+5

Source: https://habr.com/ru/post/1629369/


All Articles