Adding Player Sprite as Spacecraft in SFML / C#

We will create a new class called Player. This Player is our user-defined type to create player objects in the game. 

First of all, let's create a file named Player.cs and then write this class. This class will contain one sprite as a field and methods are a constructor, update and draw methods at first. In the constructor, we create a sprite game object using new and then load the texture of player spacecraft from TextureManager class directly.

We just defined the update method but there is no code in the code block for now. In the next, we are going to use changing of sprite's positions and other necessary things. 

Finally, we defined the draw method and also need one parameter to draw the player on the screen. RenderTarget is an abstract class and it can take reference of RenderWindow class:

using SFML.Graphics;
using SFML.Window;

namespace shmup {
    class Player 
    {
        private Sprite sprite;
        
        public Player () 
        {
            sprite = new Sprite();
            sprite.Texture = TextureManager.PlayerTexture;
        }

        public void update() { }

        public void draw(RenderTarget window) 
        {
            window.Draw(this.sprite);
        }
    }
}
Now, we can use Player class in our Game class:
    class Game
    {
        ...

        Sprite background;
        Player player;

        public Game()
        {
            ...

            player = new Player();
        }}
In conclusion, we draw this player object on the screen:
        private void draw() 
        {
            this.window.Clear(Color.Blue);
            
            this.window.Draw(this.background); 
            this.player.draw(this.window);

            this.window.Display();
        }
    }
}
The result:
Adding Player SFML

No comments:

Post a Comment