Search code examples
c#xna

C# XNA - Start draw from bottom-center


Normally XNA start drawing sprite from top-left, but I would like to start draw object from bottom-center, how this could be done?


Solution

  • You want to specify a different origin in your SpriteBatch.Draw calls. The default is 0,0 (top-left). Note that the origin is relative to the sprite, not the screen.

    So if your sprite is 64x64, you want to use an origin of 32x64 for bottom center.

    e.g. using this override (MSDN)

    spriteBatch.Draw (
             texture,
             position,
             sourceRectangle,
             color,
             rotation,
             new Vector2(32, 64), // origin
             scale,
             effects,
             layerDepth
    )
    

    You can calculate these on the fly if you wish. e.g if you're using the full texture you could specify it as new Vector2(texture.Center.X, texture.Height). Or alternatively you could base it on the sourceRectangle if you're using a sprite sheet.

    You need to specify a bunch of other arguments to use these Draw overrides but you can just pass in the defaults. The defaults are:

    sourceRectangle: null = full texture
    color: Color.White = default color (sprite colors will be used)
    rotation: 0f = no rotation
    scale: 1f = default scale
    efects: SpriteEffects.None = no flipping
    layerDepth: 0 = default layer