Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top