libgdxdragspritebatch

Dragging a texture (without jump)


How can I drag a texture (image) without making it jump and centering itself on the mouse cursor (what I have below in my code)?

When I click on the texture, nothing should happen, and when I drag, the mouse cursor should stay in place (relative to the edges of the texture).

Example: https://s31.postimg.org/ojapwbj6j/Untitled_1.jpg

SpriteBatch batch;
Texture texture;
OrthographicCamera camera;
Vector3 spritePosition = new Vector3();

float offsetX, offsetY;
Vector3 input;

@Override
public void create () {

    batch = new SpriteBatch();
    texture = new Texture("badlogic.jpg");
    camera = new OrthographicCamera();
    camera.setToOrtho(false);

}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(texture, spritePosition.x, spritePosition.y);
    batch.end();

    if (Gdx.input.justTouched()){

            int x1 = Gdx.input.getX();
            int y1 = Gdx.input.getY();
            input = new Vector3(x1, y1, 0);
            camera.unproject(input);

            offsetX = x1 - spritePosition.x;
            offsetY = y1 - spritePosition.y;

    }

    if (Gdx.input.isTouched()) {

        spritePosition.set(Gdx.input.getX() - offsetX, Gdx.input.getY() - offsetY, 0);

    }

}

Solution

  • What you need to do is work out the offset of the mouse position relative to your image, and subtract that, rather than half the width / height as you're doing at the moment.

    Here's some very rough pseudocode to show what I mean - You'll need to rewrite as Java...

    if Gdx.input.justTouched {
        get mouse position from Gdx.input
        camera.unproject it into cameraX and cameraY
        offsetX = cameraX - imageX
        offsetY = cameraY - imageY
    }
    
    if Gdx.input.isTouched {
        spritePisition.set(Gdx.input.getX() - offsetX, Gdx.input.getY - offsetY)
    }