How to drag and drop a LibGDX Image actor

drag-and-drop, java, libgdx

Solution

I went digging through the LibGDX source for `com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop` and found the answer. The code places the payload +14 in the X direction from the cursor and (-20 - payLoadActor.getHeight()) in the Y direction which is why I'm not able to visually drag the payload. There is a `setDragActorPosition` method that can be used to correct the position. If you always want the dragged payload to be centered under the cursor you can do:

final DragAndDrop dragAndDrop = new DragAndDrop();
dragAndDrop.setDragActorPosition(-(sourceImage.getWidth()/2), sourceImage.getHeight()/2);

If you want the dragged payload to maintain its placement under the cursor/finger than you have to use the cursor position when calling `setDragActorPosition` in the `dragStart` method.

final DragAndDrop dragAndDrop = new DragAndDrop();
dragAndDrop.addSource(new DragAndDrop.Source(sourceImage) {
    public DragAndDrop.Payload dragStart (InputEvent event, float x, float y, int pointer) {
        DragAndDrop.Payload payload = new DragAndDrop.Payload();
        payload.setDragActor(sourceImage);
        dragAndDrop.setDragActorPosition(-x, -y + sourceImage.getHeight());
        return payload;
    }
    public void dragStop (InputEvent event, float x, float y, int pointer, Target target) {
        sourceImage.setBounds(50, 125, sourceImage.getWidth(), sourceImage.getHeight());
        if(target != null) {
            sourceImage.setPosition(target.getActor().getX(), target.getActor().getY());
        }
        virtualStage.addActor(sourceImage);
    }
});

Problem

I have a LibGDX scene with a couple of Images (the Actor subclass). I want to drag one Image and drop it on another. I started with the source code located at DragDropTest.java. Since I basically want the source to be the payload I've tried modifying `payload.setDragActor` to use the source Image. It kind of works, I need to add the code to place the payload actor back in the stage but that isn't my issue. My problem that that the payload (when it's the source actor or a separate actor) doesn't really get dragged. Instead what happens is the payload actor positions itself slightly down and to the right of the mouse cursor. I want to place the payload, not point to where I want the payload placed. It doesn't feel like dragging at all, it feels like something is following the cursor. I see the same behavior on the Android emulator as I do on the desktop version of the app.

Original source