Array Sorting - Which Method?

Hi, I'm new here. I have a question about array sorting algorithms, and which one would be the most efficient in my situation. I am making a simple 2D game that will be viewed from a top-down perspective, and I'm trying to decide what would be the best way to determine which objects will be drawn behind other objects. the first thing that came to mind was an array that stores the y values of the objects and draws them in that order. The problem is that many objects' y values will change. I know there are many ways to sort arrays, so my question is which one will work best in this situation?
What API are you using? If you're using a 3D API (and you should, to take advantage of today's hardware), just set the z values according to your layers. Then you don't have to sort anything on your own.
I'm using SDL. I was kind of hoping to do everything without a 3D API.
I don't know if SDL provides a way to do that (it probably does), as I've never used it. One way to solve it would be to store each layer in a different array (or use a three dimensional array). Then you could draw them in the correct order without the need to sort anything.
I don't think that would solve the problem. If the player is in front of an object, I want to draw them later so that the object wouldn't be covering them. If the player is behind the object, I want to do the opposite. The depth value of objects that move will change from frame to frame, so they have to be sorted.
You're right.

Let's see. Maybe there's a simpler way, but you could divide objects whose top part can hide the characters into two sprites, giving them different z values. If characters are no higher than two tiles, as is common, I think this would work.

I'm interested in this because I too am writing a similar game, although I'm using DirectX, but I haven't got to that part yet. I'd like to avoid having to sort characters by their Y value everytime any of them moves.
Last edited on
I considered doing that, but I feel like it would limit the gameplay. I want to try it this way first, so could you suggest a specific sorting algorithm?
In a top-down view, can there even be objects "behind" another object? Below an object I can imagine (such as under a large tree).
If the game has an isometric view, it's different. In that case specifying a draw order is fairly easy if you limit your z values to multiples of a tile border length.
ChrisR wrote:
could you suggest a specific sorting algorithm?

std::sort can sort arrays. The second argument passed must be a pointer to one past the last element of the array.
Athar wrote:
In a top-down view, can there even be objects "behind" another object?

I assume we're talking about something like the old Final Fantasy and Phantasy Star games. Not exactly top-down, though.
Topic archived. No new replies allowed.