Search code examples
libgdxscene2d

Libgdx create sequence action programmatically


In my libGDX application I have an actor which needs to create actions programmatically.

At the minute I am adding moveBy actions with incrementing delays in order to get the desired effect but this is very inefficient. Something like below;

actor.addAction(sequence(delay(i * DELAY), moveBy(50, 50));

If possible I would like to programmatically create one single sequence action and add moveBy actions to it as needed. Then I could just invoke a single action without having to continually add actions which is very unresourceful.

I have checked the documentation and could not find anything specific to my particular need.

I was thinking something along the lines of (pseudo code);

addPath(Vector2 path) {

    paths.add(path);
}

invokePathAction() {

    Action sequence = sequence();
    for all paths
        sequence.add(moveBy(path.x, path.y, TIME));

    addAction(sequence);
}

Is something like this possible with libGDX?


Solution

  • Of course - there is addAction method in the SequenceAction class

        MoveToAction action1 = new MoveToAction();
        action1.setPosition(0, 0);
        action1.setDuration(2);
    
        MoveToAction action2 = new MoveToAction();
        action2.setPosition(-500, 0);
        action2.setDuration(2);
    
        ...
    
        SequenceAction sequence = new SequenceAction();
    
        sequence.addAction(action1);
        sequence.addAction(action2);
    
        ...
    
        actor.addAction(sequence);
    

    if you want to clear all actions and have "empty" sequence again you can call

        sequence.reset();