Thursday, 10 February 2011

XNA Game services

I read a good analogy recently explaining the concepts of Game Components and Game services. Game components are like the plumbing (or sewage depending on how good your code is) system underneath a city that is your game. The components are interconnected through the Game class, but can exist independently to certain extent. Game Services are like have a Large Zeppelin over the city with rope ladders that can you can use to grab elements that you need to reference in your game objects. You climb up the rope ladder and grab the type of object that you want. Game services allow you to share objects registered as Game services across Game components. It is reserved for items that a Game Component might need to preform a function

Here is how to use game services. You set up your objects in the main game

Say you want to use a common sprite batch that is set up in your main Game class

spriteBatch = new SpriteBatch(GraphicsDevice);

this.Services.AddService(typeof(SpriteBatch), spriteBatch);

the typeof function says what kind of ladder you will be using to access the service later.

then in the class that you want to retrieve it from (in this case a game drawable component) 

public ChaseImage(Game game, Texture2D CircleImage)
: base(game)
sp = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
image = CircleImage;
spriteFrame = new Rectangle(0,0, image.Width/4, image.Height/4);
imagePosition = new Vector2(LocalRand.RMinMix(0, 40), LocalRand.RMinMix(0, 40));

then you can use the shared sprite batch to draw the all components thus

public override void Draw(GameTime gameTime)
sp.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise,null, SpriteScale);

sp.Draw(image, spriteFrame, null, new Color(new Vector4(1,1,1,0.02f)),1.0f,Vector2.Zero,SpriteEffects.None,1);




  1. If you have a collection of similar services all with the same typeof you could use the generic search code presented in the previous post to retrieve each of the services.

  2. This method only uses one sprite batch but still has multiple calls to the sprite batch for each component drawn.

No comments:

Post a Comment