OK so we talked about layered background structure in 2D games in the first post and implemented 2 simple types; Fixed Background and Tiled Background. Although I keep saying them simple , those two are probably the most used types too. Especially Tiled Background is standard for top down or isometric view games.
In this post , we’ll talk about and implement two another types , Big Huge Background ( I honesty have no idea what to call it ) and Flowing Background ( I know I’m terrible at naming stuff ). ( Edit : I just decided to do Flowing Background in another post )
Big Huge Background
Let’s start with this one. Now you know sometimes they have a big environment in the background , like a city , and you slowly move on that background. That is exactly what we’ll going to do now. It’s pretty simple actually , only thing is , you have to be careful about X and Y Coordination of Camera. Have a look at this ;
As you can see , what are we supposed to do is , get a particular section of background image ( starting from Camera.X / Camera.Y and ending at Camera.X + 500 / Camera.Y + 500 ) and draw it on screen ( starting from 0 / 0 and ending at 500 / 500 )
Let’s have a look at the code ;
{
privateTexture2D _texture;
privateRectangle _screenRectangle;
privateRectangle _cameraRectangle;
public BigHugeBackground(Texture2D texture)
{
_texture = texture;
}
publicvoid Update(Rectangle screenRectangle, Rectangle cameraPosition)
{
_screenRectangle = screenRectangle;
_cameraRectangle = cameraPosition;
}
publicvoid Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(_texture, _screenRectangle, _cameraRectangle, Color.White);
}
}
Again we have a texture for background ( Texture2D class also holds Width and Height data of that image ) , _screenRectangle which holds the data for camera Width and height and _cameraRectangle which hold the data for Camera.X and Camera.Y.
Actually if you’re going for something simple like one view full screen , then you can get _screenRectangle data from _cameraRectangle too. But if you ever want to resize your camera view , say use top half of the screen for the game and bottom half for hud , then you’ll need both of them.
Nothing fancy in constructor and Update methods really. And as I said earlier , draw method just takes a section of image ( _cameraRectangle ) and draws it on whole game screen ( _screenRectangle ).
So now it should look something like this ;
Please don’t mind the terrible background , it just makes it easy to debug movement and position related stuff.
I was planning to write about Flowing Background too but I think it would be better to keep posts shorter from now on. So I’ll talk about Flowing Background in another post.
You can find a sample Visual Studio Solution below , it contains both BigHugeBackground and FlowingBackground ( and the other 2 from previous post ).
Hope you like it!
Visual Studio 2010 Solution