Beckham Beckham - 5 months ago 11
Android Question

Dragging image fix (libGDX)

I'm trying to make a draggable image, still can't get the result. The image jumps on the Y-axis when I click on it.

My coding attempt:

public class MyGdxGame extends ApplicationAdapter {

SpriteBatch batch;
Texture img;
Sprite sprite;
float offsetX;
float offsetY;

@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
sprite = new Sprite(img);
sprite.setPosition(200,200);

}

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

batch.begin();
sprite.draw(batch);
batch.end();

if (Gdx.input.justTouched()) {

offsetX = Gdx.input.getX() - sprite.getX();
offsetY = Gdx.input.getY() - (Gdx.graphics.getHeight() - (sprite.getY() + sprite.getHeight()));

}

if (Gdx.input.isTouched()){

sprite.setPosition(Gdx.input.getX() - offsetX, (Gdx.graphics.getHeight() - Gdx.input.getY()) - offsetY);

}

}

}


This is the result I'm getting:

example

How do I fix it?

Answer
offsetY = Gdx.graphics.getHeight() - Gdx.input.getY() - sprite.getY();

should work

Comments