Remove Actors from Stage?

杀马特。学长 韩版系。学妹 提交于 2019-12-03 06:08:17

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.

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

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