0
\$\begingroup\$

From what I understand, in order to show all elements of a 2D game in the proper way, I need to render them in order, from the further away from the camera to the closest. So I should sort them by depth before displaying them. Since sorting a list 60 times per second seems kinda clunky, would it be a better idea to store the objects to render in a binary search tree? Is there an ideal way to do store these objects? Or did I get something wrong? about this?

\$\endgroup\$
2
  • \$\begingroup\$ How much does your ordering change from one frame to another? Sorting an almost-sorted list (apart from the few objects that changed places since last frame) can be much faster than sorting a list that's in random order. \$\endgroup\$
    – DMGregory
    Commented Jan 16, 2021 at 13:13
  • \$\begingroup\$ Sorting will be the least of your problems. profile it first before you think about optimizing it \$\endgroup\$
    – Raildex
    Commented Jan 16, 2021 at 17:05

1 Answer 1

1
\$\begingroup\$

I would implement a Z level system: create a draw_texture function that takes the Z level of the object (which could be determined by its position), and instead of rendering, store the texture and src/dst rects in an array representing the Z level (you could have one array for each level, or a matrix, where each row would be a Z level).

Then create a function to render all of then (just go through the matrix, rendering each texture), and call it before sdl_present().

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is actually more or less what I ended up doing: I've got generic Entity instances, which are just containers of components and are stored unordered in a vector. One type of component is the DrawComponent, which encapsulates the renderable part of an entity (a sprite, a shape, etc). During the update phase of an Entity instance, if it has a DrawComponent, this one adds the data that has to be rendererd to a buffer, which is just a C++ multiset sorted by depth. When the update phase is over, the multiset is iterated over to render each of its elements and then it gets emptied. \$\endgroup\$
    – Gian
    Commented Feb 13, 2021 at 10:24
  • \$\begingroup\$ Not really sure this is the right way of doing this, but I'm figuring out this kind of stuff as I go. Most likely this system can be significantly improved, but I like it so far. \$\endgroup\$
    – Gian
    Commented Feb 13, 2021 at 10:28
  • \$\begingroup\$ I had another idea, very similar, but I think the code would be clearer, don't know if it would be more or less efficient though. The idea would be to create one texture for each level and then render directly to that texture acording to the object Z level, then just render the textures to the screen in order. This way, you don't need to store a lot of data to render later. \$\endgroup\$ Commented Feb 26, 2021 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .