15

I'm developing a game using libGDX and I would like to know how I can drag and drop an Actor. I've made my stage and drawn the actor, but I don't know how to trigger that event.

Please try to help me using my own architecture.

public class MyGame implements ApplicationListener 
{
    Stage stage;
    Texture texture;
    Image actor;

    @Override
    public void create() 
    {       
        texture = new Texture(Gdx.files.internal("actor.png"));
        Gdx.input.setInputProcessor(stage);
        stage = new Stage(512f,512f,true);

        actor = new Image(texture);
        stage.addActor(actor);
    }

    @Override
    public void render() 
    {       
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }
}
James Skemp
  • 8,018
  • 9
  • 64
  • 107
Juan Mitchell
  • 602
  • 1
  • 8
  • 20

3 Answers3

13

If you don't want to use DragAndDrop class, you can use this:

actor.addListener(new DragListener() {
    public void drag(InputEvent event, float x, float y, int pointer) {
        actor.moveBy(x - actor.getWidth() / 2, y - actor.getHeight() / 2);
    }
});

Edit: method drag instead touchDragged

Michal Lonski
  • 877
  • 1
  • 11
  • 20
pablo2303
  • 171
  • 1
  • 8
12

Take a look at the Example in the libgdx examples. Here is the drag and drop test from the libgdx test classes: DragAndDropTest

If you just want to drag/slide your Actor around you need to add a GestureListener to it and pass your Stage to the Inputprocessor like this:Gdx.input.setInputProcessor(stage);. Here is the GestureDetectorTest from libgdx. For drag events its the Flinglistener.

Chase
  • 3,123
  • 1
  • 30
  • 35
bemeyer
  • 6,154
  • 4
  • 36
  • 86
2

In your main gamescreen class add a multiplexer so you can access events from different classes:

private InputMultiplexer inputMultiplexer = new InputMultiplexer(this); 

After the gamescreen constructor add as an example:

inputMultiplexer = new InputMultiplexer(this);      
inputMultiplexer.addProcessor(1, renderer3d.controller3d);  
inputMultiplexer.addProcessor(2, renderer.controller2d);
inputMultiplexer.addProcessor(3, renderer3d.stage);
Gdx.input.setInputProcessor(inputMultiplexer);

In your class that is using the actors use a DragListener as and example:

Actor.addListener((new DragListener() {
    public void touchDragged (InputEvent event, float x, float y, int pointer) {
            // example code below for origin and position
            Actor.setOrigin(Gdx.input.getX(), Gdx.input.getY());
            Actor.setPosition(x, y);
            System.out.println("touchdragged" + x + ", " + y);

        }

    }));
GothicFan
  • 86
  • 4