从舞台上移除演员?

我使用LibGDX并在我的游戏中只移动相机。 昨天我创造了一种在游戏中占据一席之地的方法。 我正在尝试克隆Flappy Bird,但我在绘制正在屏幕上移动的地面时遇到了问题。 在每次渲染调用中,我都会向Stage添加一个新的Actor ,但是几次之后绘图就不再流动了。 每秒帧数下降得非常快。 还有另一种方法可以在游戏中取得进展吗?

如果我正确阅读,你的问题是,一旦演员离开屏幕,他们仍然处理并导致滞后,你希望他们被删除。 如果是这种情况,您可以简单地遍历舞台中的所有演员,将他们的坐标投影到窗口坐标,并使用它们来确定演员是否在屏幕外。

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

如果演员x在窗口中坐标加上它的宽度小于0,则演员已完全滚动离开屏幕,并且可以被移除。

@kabb稍微调整一下解决方案:

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

根据我的经验,在迭代actor.remove()时调用actor.remove() 将打破循环 ,因为它正在从正在迭代的数组中删除actor。

一些类似数组的类会在这种情况下抛出ConcurrentModificationException作为警告。

所以…解决方法是告诉演员稍后Action 删除自己

  actor.addAction(Actions.removeActor()); 

或者……如果你因为某些原因迫不及待地想要移除actor,你可以使用SnapshotArray

  SnapshotArray actors = new SnapshotArray(stage.getActors()); for(Actor actor : actors) { actor.remove(); } 

从其父级中删除actor的最简单方法是调用其remove()方法。 例如:

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