Scene2d how to handle touched actor?(LibGDX)

六眼飞鱼酱① 提交于 2019-12-29 08:45:47

问题


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 me if actor was touched or released. In my game, when actor is pressed and hold, some things should be done every frame, not only in one moment that I put my finger on it. I want to stop the things when I release my finger.


回答1:


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.




回答2:


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;
        }

    });



回答3:


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);


来源:https://stackoverflow.com/questions/19071834/scene2d-how-to-handle-touched-actorlibgdx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!