Search code examples
javalibgdx

Libgdx return moving image back to original position


I have this image displayed on the screen from an array (at 50,100) where when the user touches that image, it moves to a different position on the screen (100,200), I want to know how can the user touch that same image again and it moves back to the original position.

        final Image img = pic.get(0);
        pic.get(0).addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("CLICKED!!!");
                img.addAction(Actions.moveTo(300,700));
            }
        });
   }

Solution

  • Save the previous Position.If the image by clicked not on the previous position go back to the previous Position else go to the new position:

    final Image img = pic.get(0);
    final float prevX = img.getX(), prevY = img.getY();
    
    img.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            System.out.println("CLICKED!!!");
            if(img.getX() != prevX || img.getY() != prevY)
                img.addAction(Actions.moveTo(prevX, prevY));
            else
                img.addAction(Actions.moveTo(300,700));
        }
    });