Instead of iterating ALL the game objects, you should iterate only the viewable objects
.
So, how to do that?
->> METHOD 1 (slow, but simple) <<-
First, separate your game logic in 2 pieces: updateView()
, and draw()
.
updateView():
Here, you calculate
what objects are inside the screen, and add them to a simple List
(you can choose ArrayList
or LinkedList
, each one will have different performance impact, so, benchmark them!).
draw():
Here, you iterate over all the objects on the List
you created before on updateView
, and draw
them.
->> METHOD 2 (fast, but complex) <<-
The basic logic is somewhat like Method 1: you have the viewable objects inside a List, and draw them on draw()
method. But the difference between these methods is that, on this method, instead of each tick verify what objects are viewable, you check when the objects move
.
Depending on how your Game Objects are managed, Method 1 can be faster
(if your Game Objects are moving every time, like particles
), but for general purposes, this method is faster
.
So, inside Game Object, you add a boolean called addedToViewList
. This boolean indicates whether the object is added to the viewable objects list
, so we don't need to use list.contains(object)
and iterate over it. Then, every tick, you check if the object is already on the list. If it is, you check if he is viewable or not: if not, you remove
him from list. If he wasn't on the list, but he is viewable, then you add
him to list.
Example:
public void onMove() {
if (addedToViewList && !insideScreenView()) {
this.addedToViewList = false;
(view list).remove(this);
}
else if (!addedToViewList && insideScreenView()) {
this.addedToViewList = true;
(view list).add(this);
}
}
Hope I helped you. See ya!