Creating a Player Class

After creating a scrolling background, next would be to create the player character. Earlier in my coding plan I decided to make a player class in order to encapsulate all the functionality the of the player object.

iOS Simulator Screen Shot 11 May 2015 14.34.32
Implementing the player into the scene

Although this approach took more work than the way I implemented the background it means that the code is cleaner, as all the player code is kept in one tab, and hopefully this will be useful in the future to stop the code becoming too messy. Next was to add in a floor and make the player interact with it. I did this by adding in gravity to the scene and physics to both the floor and the player object. In SpriteKit this is quite easy by using the properties of the SKSpriteNode. First you need to assign the node a physics body, and then you can set this to be dynamic meaning that it can be affected by physics.

So by giving the floor a physics body that isn’t dynamic and the player a physics body that is, the floor can be detected by the player and collide with it but the floor will not move. By adding a velocity vector to the player the player can then run across the screen. Then by adding gravity to the game using:

 physicsWorld.gravity = CGVector(dx: 0.0, dy: -9.8)
physicsWorld.contactDelegate = self

iOS Simulator Screen Shot 11 May 2015 14.34.38
The effects of adding gravity to the game

Now the player can run on the floor and falls off when the floor ends. There are still some bugs to this test simulation but it will be useful to have proper assets for the game in place before fixing these.