Sign in to follow this  
LordRhys

Render order for objects

Recommended Posts

 I used a technique that was in an XNA TileEngine tutorial by Nick Gravelyn where a renderlist is created and a sort done based on a comparison between object origins. This all works great between the animated sprites (player, npc's, and mobs) however my issue is with the player and non-animated objects like treasure chests and other items that may be placed. The code pieces I use are listed below, I am trying to figure out how I would also include the BaseSprite class objects. This is done so that when the player passes an npc, mob or object atthe top of that sprite he will be displayed as walking behind it.

 

private List<AnimatedSprite> renderList = new List<AnimatedSprite>();
 

    private Comparison<AnimatedSprite> renderSort =
      new Comparison<AnimatedSprite>(renderSpriteComapre);
   
    // also have BaseSprite chestSprite as non-animated sprite object

    BaseSprite chestSprite = new BaseSprite(
                containers,
                new Rectangle(0, 0, 32, 32),
                new Point((int)c.Value.X, (int)c.Value.Y));
   
    renderList.Add(npc.Sprite);
    renderList.Add(mob.Sprite);
    renderList.Add(player.Sprite);
   
    private static int renderSpriteComapre(AnimatedSprite a, AnimatedSprite b)
    {
        return a.Origin.Y.CompareTo(b.Origin.Y);
    }   
   
    public override void Draw(GameTime gameTime)
    {
      //spritebatch.begin info
      //draw level code
     
      renderList.Sort(renderSort);


 

      foreach (AnimatedSprite s in renderList)
        s.Draw(gameTime, GameRef.SpriteBatch);
     
      //spritebatch.end info     
    }
    

Edited by LordRhys

Share this post


Link to post
Share on other sites

If it's possible to render all these objects in one batch operation, have you tried the SpriteSort modes in SpriteBatch? The ones that are relevant here are BackToFront and FrontToBack. It works with the LayerDepth value, which is like a Z-index for your sprites.

 

Barring that, change your list of objects from AnimatedSprite to BaseSprite, and also accordingly in your comparison function. If AnimatedSprite inherits from BaseSprite, this ensures that you can sort all the sprite objects together.

Share this post


Link to post
Share on other sites

Thanks, I'll look into the SpriteSort modes first, AnimatedSPrite and BaseSPrite classes are seperate base classes, I will alo slook into refactoring them into having AnimatedSPrite inherit from BaseSprite.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this