I coded up a simple 2D Camera for my HTML5 Canvas-Based Game Engine but I noticed the performance wasn't very good. So a lot of people suggested only rendering things that are shown by the camera but I haven't found anything that helps how to implement this.

I'm thinking about iterating over through all my game entities then checking their rendering positions, etc. But is this efficient?

if(renderCoords[i].x >= 0 && 
   renderCoords[i].y >= 0 && 
   renderCoords[i].x <= camera.getWidth()+camera.offset.x && 
   renderCoords[i].y <= camera.getHeight()+camera.offset.y) {

It's not tiled-based, just thought I mentioned that. Just doesn't seem clean to me.


For a small 2D game, there nothing inherently wrong with this approach. Rendering is indeed costly, but looping over objects shouldn't be an issue (except if you really have tons of them, then look for a good space partitioning scheme). So keeping your rendering loop and discarding objects with such a test should be fine.

I'm not sure about your conditions though, especially what that camera offset is supposed to be (is that a camera position?)... But your general idea is OK.

And the classical advice: profile before you optimize, re-profile when done, and make sure your changes give you a significant improvement.

| improve this answer | |
  • \$\begingroup\$ First, thanks for answering. I only expect about 10-40 objects so it's pretty small I think. The camera offset is pretty much the position of the camera. I'm just translating the canvas to different positions. Also, thanks about the profiling. \$\endgroup\$ – Maxxxx May 28 '12 at 21:44
  • \$\begingroup\$ @Maxxxx Oh, are you using some library? I'm mostly wondering about the renderCoords[i].x >= 0 test, shouldn't it be more renderCoords[i].x >= camera.offset.x-camera.getWidth()? \$\endgroup\$ – Laurent Couvidou May 28 '12 at 21:48
  • \$\begingroup\$ No, I'm not using any library. And I think you're right about the code. Because if it's 'renderCoords[i].x >= 0' then when the camera offset goes something like -150 it won't render I think. \$\endgroup\$ – Maxxxx May 28 '12 at 21:55
  • \$\begingroup\$ ... and you could render objects that are out of scope. \$\endgroup\$ – Laurent Couvidou May 28 '12 at 21:59
  • \$\begingroup\$ What exactly do you mean by "out of scope"? \$\endgroup\$ – Maxxxx May 28 '12 at 22:06

It's not clear to me that your code above is correct, should the bounds not be camera.offset.x and camera.getWidth() + camera.offset.x (and similar for Y)?

It might make more sense in the code, to assign local variables to the viewport leftx, topy, rightx, bottomy and then test if the objects bounding-boxes are in that range.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.