Q:

Sort Polygons in order - not working?

I'm fairly new to programming in a 3d world.
I'm trying to create a canvas where all the objects are drawn in order of furthest-to-closest and from bottom to top - so they don't overlap each other, but there are problems.

As you can see, some of the objects are overlapping each other. None of the objects in the screen will be moving so I was wondering: is there an algorithm available to sort the objects in the correct order?
At the moment I have them sorting in the Z axis ascending, then X descending and Y descending.

A:

As @dreta mentioned in the comments, the typical way 3D engines solve this is with a depth buffer and using the hardware depth test, which allows you to draw arbitrarily-shaped objects in any order and will keep track of the closest surface at each pixel.  Manually sorting objects is also possible, but will not necessarily handle nonconvex objects or overlapping objects correctly.
However, if you do want to sort objects, you'll need to calculate a depth value for each object, then sort by descending depth.  To get the depth, if you're using a typical 3D engine setup, you'll need to transform each object's center point through your view matrix (which goes from world space to view space), then take the negative of the Z coordinate of the result.  (Negative because in right-handed coordinates with X and Y aligned with the screen, Z will be pointing out of the screen.)
If it's always an isometric view like this, you can probably get away with calculating depth = ±X ± Y - Z, where the ± means: pick the sign that makes depth increase as you get further away from the camera.  That will depend on the orientation of your X and Y axes.

