Smooth Movement of Player in SFML / C#

In this post, we'll see how to use a key handler for the player. We need to move the player spacecraft with the keyboard. 

Let's improve our Player class. I'm going to add a method called keyHandler. This method control some keys that pressed from the keyboard. If the player presses key "a" then the spacecraft should move left. That's a classic movement mechanic.

The player should make smooth movements. Therefore, I decided to use Keyboard.IsKeyPressed.

Firstly, I declared two fields in the Player class.
namespace shmup {
    class Player 
    {
        private Sprite sprite;
        public const float PLAYER_SPEED = 4f;
        Vector2f position;
After that, I wrote a keyHandler method in Player class, and then I called it in the update method.
        public void keyHandler()
        {
            bool moveLeft = Keyboard.IsKeyPressed(Keyboard.Key.A);
            bool moveRight = Keyboard.IsKeyPressed(Keyboard.Key.D);
            bool moveUp = Keyboard.IsKeyPressed(Keyboard.Key.W);
            bool moveDown = Keyboard.IsKeyPressed(Keyboard.Key.S);

            bool isMove = moveLeft || moveRight || moveUp || moveDown;

            if(isMove)
            {
                if(moveLeft) position.X -= PLAYER_SPEED;
                if(moveRight) position.X += PLAYER_SPEED;
                if(moveUp) position.Y -= PLAYER_SPEED;
                if(moveDown) position.Y += PLAYER_SPEED;
            }   
        }

        public void update() {
            this.keyHandler();
            this.sprite.Position = position;
        }
Maybe, it's not really good usage, but at this point who cares like me. Finally, we have to just call the update method of player in the update method of game class and there is it:
smooth movement of player in sfml
It looks not really smooth in gif but it's just related quality of the gif.
 

No comments:

Post a Comment