Bright Hub
 
Matthew Casperson's Hubfolio

SDL Programming Tutorial - Adding a player

Article by Matthew Casperson (4,883 pts )
Published on Sep 16, 2009

In this article we add a ship to the screen that can be controlled with the mouse.

The pretty scrolling background we implemented in the last article is nice, but it doesn't make for a game. In order for there to be a game we need a ship character for the player to interact with.

Player.cpp / Player.h

The Player class extends the VisualGameObject class, because it is going to draw an image to the screen. At the moment it is a very simple class, overriding the new MouseMotion function added to the BaseObject class (more on that later) to position the Player under the mouse pointer. It also does some bounds checking to make sure the Player never leaves the screen.

BaseObject.cpp / BaseObject.h

In order for the game elements to have the ability to respond to mouse events, the BaseObject class gets a new function called MouseMotion. This function is called by the EngineManager when some change in the state of the mouse has been detected. Like the Draw and EnterFrame functions, the MouseMotion has an empty implementation, meaning that classes can override the function if they choose to, or ignore it if they have no need to receive mouse events.

EngineManager.cpp / EngineManager.h

The EngineManager needs to be modified to detect and distribute mouse events in the render loop. When such a mouse event is found the MouseMotion function on all current BaseObject classes is called. [code]

ApplicationManager.cpp / ApplicationManager.h

Finally the ApplicationManager is modified to create a new instance of the Player class. [code]

Thanks to the framework we established in the first article, adding new elements like the Player become quite easy. Extending the BaseObject/VisualGameObject classes gives us the ability to add a sprite to the screen with only a few lines of code, and by adding new functions to the BaseObject class, and watching for new events in the EngineManager, we can respond to new types of events.

Download the source code here.

Read more in the SDL Programming Tutorial series

Related Files

Search More About:

 
Follow Matthew Casperson
Receive weekly updates from Matthew Casperson
 
Bright Hub - Science & Technology Articles, Buyer's Guides, How-To Tips and Software Reviews
About Bright Hub | Contact Us | Advertise with Us | Become a Writer | RSS | Site Map | Terms of Use | Privacy Policy | Copyright Policy
©2009 Bright Hub Inc. All rights reserved. Page copy protected against web site content infringement by Copyscape