Drawing the Space Game Background in SFML / C#

In this post, We are created first manager to keeping organized and loading textures in the game and drew our background to represent space environment on the screen.

Firstly, I need some textures to use in my game. You can find too many 2D game assets from any assets market. I prefer to draw myself. I just drew an enemy spacecraft and a player spacecraft and also a space background. I used Aseprite to draw them.

These textures should be located on bin/Assets/Textures. So, I created an Assets folder and Textures folder in the Assets folder.

So let's create a TextureManager class in shmup console application and load the images to as a texture:

using System;
using SFML.Graphics;
using SFML.Window;

namespace shmup
{
    class TextureManager
    {
        private static string ASSETS_PATH = "bin/Assets/Textures/";
        static Texture playerTexture;
        static Texture enemyTexture;
        static Texture backgroundTexture;

        public static Texture PlayerTexture { get {return playerTexture; } }
        public static Texture EnemyTexture { get {return enemyTexture; } }
        public static Texture BackgroundTexture { get {return backgroundTexture; } }

        public static void LoadTexture()
        {
            playerTexture = new Texture(ASSETS_PATH + "player.png");
            enemyTexture = new Texture(ASSETS_PATH + "enemy.png");
            backgroundTexture = new Texture(ASSETS_PATH + "background.png");
        }  
    }
}
Let's take a look code above. We created TextureManager to manage our textures. Also we can add new textures if we want. It's gonna be really useful and can be developed further. I specified path of Textures folder according to Program.cs file. To loading textures, we are going to use LoadTexture static method in Game constructor. 

Let's go to Game class and define sprite called background as field. This sprite is actually our game object and Sprite class is built-in class in SFML.Graphics. After that, let's move in constructor and load textures and then call the background texture that loaded from TextureManager to load in sprite
	...

	Sprite background;
	
        public Game()
        {
            ...

            TextureManager.LoadTexture();
            
            background = new Sprite();
            background.Texture = TextureManager.BackgroundTexture;
        }
        
        ...
Finally, we can draw background on the screen:
	...

	private void draw() 
        {
            this.window.Clear(Color.Blue);

            this.window.Draw(this.background);
            this.window.Display();
        }
The resulting output should be:
Space Background in Shmup Game


No comments:

Post a Comment