libgdxdrag-and-dropactorclicklistener

Setting position before button is pressed Libgdx


In my create() method I created a table and inserted some Buttons like in the pic below.

http://www2.pic-upload.de/thumb/29190899/Unbenannt.png

Every time a user presses the button, a new drag-able texture should appear underneath his finger/button position.

I tried the following:

sourceImage.addListener(controller);
testbutton.get(2).addListener(new ClickListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int    pointer, int button) {
            sourceImage.setVisible(true);
            sourceImage.setPosition(vec.x, vec.y);
            return super.touchDown(event, x, y, pointer, button);
        }

    });

This worked well, but I want to make it so that the user got the texture on his finger and not have to press again on it to drag it.

So I tried to place the image to the button before the touch is started.

The problem is, that I cant get the position of the table button, because the table will be rendered after the application is started, and not in the create() correct me if I am wrong.

It's returning 0,0 when I try to get the actual table position in my create()

I found a solution in the forum: Getting Stage coordinates of Actor in Table in libGDX

   public static Vector2 getStageLocation(Actor actor) {
    return actor.localToStageCoordinates(new Vector2(0, 0));
}

and in my render()

vec = getStageLocation(testbutton.get(2));

It's giving me the correct position of the button in my table, but I don't know when and where I have to set the position of the texture before the button is pressed?


Solution

  • You are correct in that you need to use the localToStageCoordinates method to get the stage position of an actor in a table, and also that this method won't produce the desired results until after the stage/table has been rendered at least once, which is when the coordinates of the table elements are set.

    One possible approach is to render the screen early, one time, in the create method, after all the table elements have been added. You could call render(0) (if you're extending the Game or Screen classes), or call the draw method of the stage containing your table. After that point, localToStageCoordinates should give you the values you need, and you can continue on with your create method tasks.