Adding movement to the hero
We have a nice static scene now, but it doesn't make much of a game. Let's add some movement to the hero and make him walk over the screen. When he reaches an edge, he will turn back automatically.
The Hero2D class
So we want to add movement to the player. It is best to encapsulate all that new behavior in a class. Let's call class the Hero2D
. This class will be responsible for loading the texture, updating the position, and drawing the texture. Make sure the class inherits
from GameObject2D
class. We could make it inherit from the GameSprite
class, but we won't do that. Instead we will add a field of type GameSprite
. This is called composition
.
In the context of composition, Herb Sutter has said the following:
Prefer composition to inheritance
The reasons why will become obvious when we implement the scene graph and when we make an animated sprite. For now, just go with it.
Fields
The class has three fields, a game sprite, a direction that determines if the player...