1

I have a problem. The sprites I'm rendering aren't in the Z position I want them to be. The game I'm making is a 2D sandbox game - similar to terraria.

I make a 2-dimensional array and then iterate through it with a for-loop.

Basic code outline:

for(int x = 0; x < worldwidth; x ++){
        for(int y =  0; y < worldheight; y ++){

        //complicated calculations to check which texture it should use

        // draws background blocks
                 Sprite s = new Sprite(texture);
                 s.setSize(12, 12);
                 s.setOriginCenter();
                 s.rotate(rotation);
                 s.setPosition(x* world.blocksize, y* world.blocksize);
                 s.draw(batch);  

        //draws foreground blocks   
                 //same thing as with background blocks, only with a different texture    
            }
        }

I want the player to be between the background and foreground sprites. But if I draw it at the start or the end of the loop, it ends up at the very back or very front. I tried drawing it after the background tiles, but that didn't work. What do I do? Do I use something instead of a spritebatch for rendering the player?

Okay, second question: Is drawing tiles this way efficient? Am I doing it right, or should I use something like a tilemap?

Anuken
  • 65
  • 11
  • Tiles will layer in the order they're sent to the sprite batch renderer. Personally, I do things very similarly. static bg tiles I use the tiled maps classes. Animated bg I loop first, characters next, overlay tiles after. I have not seen any real negative impact doing things this way. But, off the top of my head, I don't know of a method to specifically set the z-index of an object. Would be good to know I guess. – Kai Qing Oct 17 '14 at 00:41
  • A side note - I pass the current window's offsets to the renderer so I can only render the elements that fall within the boundaries of the viewport. That may be why I don't see any performance loss doing it this way – Kai Qing Oct 17 '14 at 00:43
  • @KaiQing The thing is, It's hard to control the order I put the sprites in. I can make two loops - one for the front tiles, one for the back tiles, and put the player in between, but that would be very inefficient. Is there any way to put sprites in an array, sort it, and then make the batch render them? – Anuken Oct 17 '14 at 01:37
  • @Anuken That's a negligible inefficiency. That's the correct way to do it. – Tenfour04 Oct 17 '14 at 01:39
  • Right, as Tenfour said it is negligible unless you have an absolutely enormous collection of sprites for rendering and you are ignoring whether or not the items need to be rendered. Mine tend to be no more than 5 to 10 on each layer above the static bg and even if I am going nuts with fx my fps tends to stay pretty solid. Have you benchmarked performance differences between one and several loops? – Kai Qing Oct 17 '14 at 05:10

0 Answers0