The First Player
Drawing the Player
Update and Draw
The Update method is responsible for modifying an object's state based on its current condition and external factors, such as user input in this context.
The Draw method handles the rendering of an object's visual representation, if one exists, based on its internal state.
An object possessing only an Update method operates invisibly in the background, managing logic without visual output. Conversely, an object with only a Draw method is visible but remains static unless its state is altered by other entities (e.g., translation).
#pragma once
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include "engine/app.h"
namespace game {
class Player {
public:
explicit Player(ng::App* app);
void Update();
void Draw(sf::RenderTarget& target);
private:
ng::App* app_ = nullptr;
sf::Sprite sprite_;
};
} // namespace gameThe Player class holds a member pointer to the App object to access user input. It also contains a sf::Sprite member for rendering the player's 32x32 pixel texture.
Pixels Per Unit (PPU)
An important concept for this game is the PPU, which defines the pixel density per engine unit. A lower PPU value results in a larger on-screen representation. While the default PPU in this case would be 32 pixels per unit, we will use a PPU of 16 pixels per unit (or, equivalently, scale sprites by 2, resulting in 32 pixels over 2 units) to achieve a more suitable size.
Sprite Origin
SFML sprites default to an origin at the top-left corner. For ease of placement and collision detection, especially with circular shapes, we will set the origin of most, if not all, sprites to the center of their image. This is a common practice in game engine design.
Moving the Player
The player's movement is controlled using the WASD keys, allowing for 2D top-down navigation. To visually indicate the direction of travel, the player's sprite is horizontally flipped when moving left or right.
Throughout this guide, please note that we will consistently use the following coordinate system: left corresponds to negative x, right to positive x, up to negative y, and down to positive y.
Following the Player
The view of the game window is configured to follow the player's position, preventing the player from ever moving outside the boundaries of what is displayed.
Last updated