0
\$\begingroup\$

What is the most efficient way to render scene objects according to the current position of the camera (which will follow the player position)?

A friend told me that since processors are powerful these days, it is okay to set up everything virtually and then just update the surface according to what is inside the camera position, after a loop inside the sprites filtering only what should be rendered by the GPU.

But seems to me that this is taking more processing power from the CPU. Why process objects that aren’t visible by the player? What if I need to target mobile devices? What if I want to make my game available in a raspberry pi or very old computers?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ We always try to strike the balance between quality (update ALL objects ALWAYS) and performance (update only what is NEEDED). \$\endgroup\$ – Kromster Jun 15 '18 at 10:34
  • 1
    \$\begingroup\$ Looping over a few thousand objects is not going to be that big of a deal. \$\endgroup\$ – ratchet freak Jun 15 '18 at 11:42
  • 1
    \$\begingroup\$ Although trying to think about efficiency is important, your situation does not currently show any issue. Are you sure you're not doing premature optimization? \$\endgroup\$ – Vaillancourt Jun 15 '18 at 12:40
1
\$\begingroup\$

I think the key point in your question is this:

After a loop inside the sprites filtering only what should be rendered by the GPU.

A naive implementation would be

foreach(sprite in spriteList)
{
    if(IsInsideViewPort(sprite))
    {
        RenderSprite(sprite);
    }
}

While computers are extremely fast. If this lists gets huge it might start to become a problem. But I do not expect a problem until you have tens of thousands of sprites.

However, we can do much better than this naive approach.

Spatial Partitioning

Lets divide our world into cells in a grid. Every cell has a list of sprites that it overlaps with (a sprite can be overlapped by multiple cells, cells can overlap with multiple sprites). When we want to know what sprites should be rendered by the GPU we calculate what cells the camera can see. For each of those cells we take the sprites it overlaps with. These are the sprites we wish to draw.

The hard part is to keep the list of sprites inside a cell up-to-date. But we only have to do this when a sprite moves, and usually most of your sprites don't move :).

There are many techniques for spatial partitioning. A grid is the simplest form, but there are also hierarchical systems, like a k-d tree, and binary space partitioning.

\$\endgroup\$

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.