I'm working on a 2D sidescrolling game in Java. All of the blocks and enemies rendered are 32x32px. When I try to make too big levels, the game won't be able to handle them, which will make it lag extremely much. So what I'm trying to do to fix this problem is to make only the blocks visible by the camera render, and only the blocks visible by camera + 200-300px run their tick methods. That would probably make the game lag less.
The code:
All of the typed of objects have an own class which extends a class called GameObject, which gives them all of the methods they need (tick method, render, collision etc). In a class called Handler, GameObject is made into a LinkedList, like this:
public LinkedList<GameObject> object = new LinkedList<GameObject>();
Everything inside that LinkedList is runned like this...
public void tick()
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick(object);
if(tempObject.getId() == ID.MovingBlock){
velX_MB = tempObject.velX;
velY_MB = tempObject.velY;
}
}
}
...and rendered like this:
public void render(Graphics g){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
}
I've tried rendering only the blocks inside the camera by doing something like this:
private GameObject player;
for(int i = 0; i < object.size(); i++){ //searching through GameObject LinkedList
if(object.get(i).getId() == ID.Player){ //if found player
player = object.get(i);
}
}
After that, I checked if the blocks were close enough to the player to be rendered inside the render method, and if they were, I rendered them, like this:
public void render(Graphics g){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
if(tempObject.getX() <= player.getX() + Game.xsize + 200 && tempObject.getX() >= player.getX() - Game.xsize - 200){ //this row got error
tempObject.render(g);
}
}
}
But this didn't work, it gave me a NullPointerException error, pointing to the row marked in the previously shown code. The full error message:
Exception in thread "Thread-12" java.lang.NullPointerException
at game.main.Handler.render(Handler.java:53)
at game.main.Game.render(Game.java:363)
at game.main.Game.run(Game.java:302)
at java.lang.Thread.run(Unknown Source)
And that was only the render method, but I guess it would be the same when running them instead.
Thank you for taking your time..
EDIT: I fixed the null error and added my old method in both tick() and render(), but it's still lagging extremely much.