Remove Actors from Stage?
Asked Answered
C

3

17

I use LibGDX and move only the camera in my game. Yesterday I founded a way to draw the ground in my game. I'm trying to make a clone of Flappy Bird, but I have problems with drawing the ground which is moving on the screen. In every render call I add a new Actor to the Stage, but after a few times the drawing is no more flowing. The frames per second sink very fast. Is there another way to draw ground in games?

Cathee answered 1/3, 2014 at 22:53 Comment(1)
simply you want to remove actors when they are not visible?Kincardine
B
22

If I'm reading correctly, you're problem is that once actors go off the screen, they are still being processed and causing lag, and you want them to be removed. If that's the case, you can simply loop through all of the actors in the stage, project their coordinates to window coordinates, and use those to determine if the actor is off screen.

for(Actor actor : stage.getActors())
{
    Vector3 windowCoordinates = new Vector3(actor.getX(), actor.getY(), 0);
    camera.project(windowCoordinates);
    if(windowCoordinates.x + actor.getWidth() < 0)
        actor.remove();
}

If the actors x coordinate in the window plus it's width is less than 0, the actor has completely scrolled off the screen, and can be removed.

Brough answered 2/3, 2014 at 17:4 Comment(2)
It shouldn't cause much loss in performance, and the performance it gains you from removing actors more than makes up for it.Brough
Possibly have the actor do it itself in the act() method. Much easier since each actor might have specific "reasonings" to actually remove itself from the game.Puduns
P
20

A slight tweak of the solution from @kabb:

    for(Actor actor : stage.getActors()) {
        //actor.remove();
        actor.addAction(Actions.removeActor());
    }

From my experience, calling actor.remove() while iterating stage.getActors(), will break the loop, since it is removing the actor from the array that is being actively iterated.

Some array-like classes will throw a ConcurrentModificationException for this kind of situation as a warning.

So...the workaround is to tell the actors to remove themselves later with an Action

    actor.addAction(Actions.removeActor());

Alternatively...if you can't wait to remove the actor for some reason, you could use a SnapshotArray:

    SnapshotArray<Actor> actors = new SnapshotArray<Actor>(stage.getActors());
    for(Actor actor : actors) {
        actor.remove();
    }
Philosophy answered 16/8, 2015 at 19:10 Comment(0)
I
5

The easiest way to remove an actor from its parent it calling its remove() method. For example:

//Create an actor and add it to the Stage:
Actor myActor = new Actor();
stage.addActor(myActor);

//Then remove the actor:
myActor.remove();
Interrogate answered 6/1, 2015 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.