1

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?

Alex
  • 839
  • 1
  • 12
  • 24

1 Answers1

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

should work

TomGrill Games
  • 1,553
  • 2
  • 16
  • 25