I am in the middle of development of simple mini game and i started to notice some performance drops. Game is made the way that you have big room (canvas) that has 5000 x 5000
size and player is equipped with viewport camera that he can move on mouse drag. Now the problem is that if i am drawing 2000 objects for entire room, it causes significant performance drop. I was thinking if there is a way to only draw objects that are visible in your current camera area, not in entire room that player obviously doesn't see.
I tried to divide the room on sectors (regions) but that didnt work very well. Maybe someone has some thoughts on the subject.
This is rendering code for largest quantity of objects:
for(var i = 0; i < game.objects.stars.pool.length; i++) {
var current = game.objects.stars.pool[i];
game.components.star.apply(i);
game.mechanics.draw.circle(current.x, current.y, current.r);
}
What can be done to this to improve the performance in the way i described?
I have encountered this kind of problem and i solved it this way:
var in_viewport = function(x, y, margin) {
if(
x >= cam.x - margin &&
x <= cam.x + cam.w + margin &&
y >= cam.y - margin &&
y <= cam.y + cam.h + margin
) {
return true;
}
return false;
};
It could be implemented into your logic like this:
for(var i = 0; i < game.objects.stars.pool.length; i++) {
var current = game.objects.stars.pool[i];
if( in_viewport(current.x, current.y, 100) === true ) {
game.components.star.apply(i);
game.mechanics.draw.circle(current.x, current.y, current.r);
}
}
Now few words of explanation:
Margin parameter is recommended to be set to 100
, as it will help smooth the problem of "things show up out of the blue". It will simply render objects in range of 100
outside bounds of your camera, therefore even if you quickly move your camera, things should be already there, yet performance should be in very good place.
cam.x
, cam.y
, cam.w
, cam.h
inside of in_viewport
function should be altered to match your camera object naming, in case if you already have your right and bottom bound inside camera object, you can just replace x + w
and y + h
with right parameters.