Libgdx MoveToAction - 无法让它工作

时间:2014-10-21 12:52:52

标签: java libgdx scene2d

我试图使用MoveToAction来更新屏幕上的演员。然而,它似乎没有做任何事情,我找不到许多在线示例来帮助(那些我发现的建议我正确地设置它,但显然我是' m不)。我通过setPositionX方法更新positionX,并且能够通过记录确定positionX正在更新。还有什么我需要添加才能使这项工作?

public MyActor(boolean playerIsEast, int positionX) {
        setBounds(this.getX(), 140, 50, 200);
        this.positionX = positionX;
        this.setX(400);
        currentImage = AssetLoader.losEast;
        moveAction = new MoveToAction();
        moveAction.setDuration(1);
        this.addAction(moveAction);
    }

    @Override
    public void draw(Batch batch, float alpha) {
        batch.draw(currentImage, this.getX(), 140, 50, 200);
    }

    @Override
    public void act(float delta) {
        moveAction.setPosition(positionX, 140);
        for (Iterator<Action> iter = this.getActions().iterator(); iter
                .hasNext();) {
            iter.next().act(delta);
        }

    }

1 个答案:

答案 0 :(得分:0)

创建操作时,您可以在此处设置目标位置,而不是在act方法中。并且您的act方法无需处理该操作,因为它已经内置于Actor超类中。

所以看起来应该是这样的:

public MyActor(boolean playerIsEast, int positionX) {
    setBounds(this.getX(), 140, 50, 200);
    this.positionX = positionX;
    this.setX(400);
    currentImage = AssetLoader.losEast;
    moveAction = new MoveToAction();
    moveAction.setDuration(1);
    moveAction.setPosition(positionX, 140);
    this.addAction(moveAction);
}

@Override
public void draw(Batch batch, float alpha) {
    batch.draw(currentImage, this.getX(), 140, 50, 200);
}

@Override
public void act(float delta) {
    super.act(delta); //This handles actions for you and removes them when they finish

    //You could do stuff other than handle actions here, such as 
    //changing a sprite for an animation.
}

但是,最好使用池化操作来避免触发GC。 Actions类为此提供了便利方法。所以你可以进一步简化这个:

public MyActor(boolean playerIsEast, int positionX) {
    setBounds(this.getX(), 140, 50, 200);
    this.positionX = positionX;
    this.setX(400);
    currentImage = AssetLoader.losEast;
    this.addAction(Actions.moveTo(positionX, 140, 1)); //last argument is duration
}