Scene2d how to handle touched actor?(LibGDX)

后端 未结 3 1908
轮回少年
轮回少年 2020-12-21 02:44

I have a problem with using scene2d in libgdx. I can\'t find anywhere a method that allows me to check wheter the actor is touched or not. I can only find methods that told

相关标签:
3条回答
  • 2020-12-21 03:01

    I had the similar problem and moreover I needed to know the current coordinates; So I resolved the issue something like this:

    At first we extend the standard listener:

    class MyClickListener extends ClickListener {
        float x, y = 0;
    
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            this.x = x;
            this.y = y;
            return super.touchDown(event, x, y, pointer, button);
        }
    
        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            this.x = x;
            this.y = y;
            super.touchDragged(event, x, y, pointer);
        }
    }
    

    Then add an instance to the Actor:

    class MyActor extends Actor {
        private final MyClickListener listener = new MyClickListener();
        MyActor() {
            addListener(listener);
        }
        ...
    }
    

    And in a draw (act) method use the following:

    if (listener.getPressedButton() >= 0)
        System.out.println(listener.x + "; " + listener.y);
    
    0 讨论(0)
  • 2020-12-21 03:11

    you can check your input simply by do this in your render method

    gdx.app.log("","touched"+touchdown);
    

    firstly set the input processor..

    Gdx.input.setInputProcessor(mystage);
    

    then you can add input listener to your actor in the create method

    optone.addListener(new InputListener() {
            @Override
            public void touchUp(InputEvent event, float x, float y,
                    int pointer, int button) {
                    boolean touchdown=true;
                //do your stuff 
               //it will work when finger is released..
    
            }
    
            public boolean touchDown(InputEvent event, float x, float y,
                   int pointer, int button) {
                   boolean touchdown=false;
                //do your stuff it will work when u touched your actor
                return true;
            }
    
        });
    
    0 讨论(0)
  • 2020-12-21 03:25

    You can keep track of this in your InputListener. Create a boolean field isTouched, set to true when you get a touchDown, false when you get a touchUp. I use this method in my top-down shooter and it works very well.

    0 讨论(0)
提交回复
热议问题