如何在Libgdx Scene2d上拖放演员?

15

我正在使用libGDX开发游戏,想知道如何拖放一个Actor。我已经创建了舞台并绘制了角色,但不知道如何触发该事件。

请尝试帮助我使用我的架构。

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();
    }
}
3个回答

13

如果您不想使用 DragAndDrop 类,您可以使用这个:

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

编辑:使用方法drag而不是touchDragged


12

请查看libgdx示例中的示例。 这是来自libgdx测试类的拖放测试:DragAndDropTest

如果您只想拖动/滑动Actor,则需要向其添加GestureListener,并将舞台传递给Inputprocessor,如下所示:Gdx.input.setInputProcessor(stage);。 这是来自libgdx的GestureDetectorTest。 对于拖动事件,可以使用Flinglistener。


2
在您的主游戏屏幕类中添加一个复用器,以便您可以访问来自不同类的事件:
private InputMultiplexer inputMultiplexer = new InputMultiplexer(this); 

在游戏屏幕构造函数后面添加一个示例,如下所示:
inputMultiplexer = new InputMultiplexer(this);      
inputMultiplexer.addProcessor(1, renderer3d.controller3d);  
inputMultiplexer.addProcessor(2, renderer.controller2d);
inputMultiplexer.addProcessor(3, renderer3d.stage);
Gdx.input.setInputProcessor(inputMultiplexer);

在使用演员的课程中,以DragListener作为示例:
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);

        }

    }));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接