-1

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);

    }

}
Alex
  • 839
  • 1
  • 12
  • 24

2 Answers2

0

Why are you using camera.unproject?

Try this:

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

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(texture, spritePosition.x, spritePosition.y);
    batch.end();

    if (Gdx.input.isTouched()) {
        spritePosition.set(Gdx.input.getX() - texture.getWidth() / 2, Gdx.input.getY() + texture.getHeight() / 2, 0);
    }

}
Jim
  • 995
  • 2
  • 11
  • 28
0

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)
}
Phil Anderson
  • 3,146
  • 13
  • 24
  • I edited my code to match your answer. But I get half the result :) Please check this updated gif: https://s31.postimg.org/lg8nu0u2z/Animation.gif – Alex Jun 21 '16 at 06:06
  • The y-axis is inverted because the physical coordinate system is different to the logical coordinates (one's y-down and the other's y-up). Either use camera.unproject (which should fix it) or subtract the y position you end up with from the height of the screen to effectively invert it. – Phil Anderson Jun 21 '16 at 12:04