Objects to draw that are radiant?

How to draw objects that have a smaller Y axis first?

  • In my game there is a large 2D map of various objects. http://www.youtube.com/watch?v=em7xglMuWII. As you see, upon creation objects of the same type (trees for example) are placed correctly, but objects of another type (enemies) are placed on top of the no matter the position. Now, how can I arrange that everything is drawn according to it's position? Another example (the dog should be drawn before the tree, and not on top of it):

  • Answer:

    Assuming that you have an array containing every object that needs to be drawn. On each game loop you would loop through this array and call each object's corresponding draw() method to place it on the canvas. If you are doing it this way then you can use a sorting function on the array that will sort the array based on the object's Y axis value. So when the next game loop occurs the objects will naturally be drawn in the order that you need. var gameObjects = [{y:0}, {y:1}, {y:20}, {y:-4}, {y:2}]; gameObjects.sort(function(a,b) { return a.y - b.y; }); console.log(gameObjects); //gives: [{y:-4}, {y:0}, {y:1}, {y:2}, {y:20}] var l = gameObjects.length, c = 0; while(c < l) { gameObjects[c].draw(); c++: }; This way objects with small Y values will be drawn first and the last object drawn will have the largest Y value.

akled at Game Development Visit the source

Was this solution helpful to you?

Other answers

I'm just going out on a limb here and assuming that your drawing is painter style, in that something drawing first will show up behind something drawn after it. If that's the case, it's simply a matter of sorting your entities by y position before you draw. I'm assuming you have some mechanism of iterating through all of your entities. You'll have to sort every time the list get modified, which if you have continuously moving entities will probably be every frame. There are a handful of optimizations you can do with this. For one, you probably want to discard objects that aren't in your viewport at all, first. It's pretty common to put entities in tiles and then only sort those tiles. But those can come afterwards, depending on your performance issues..

Tetrad

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.