Getting Started With iOS for a C# Programmer - Part Three - Moving an Object

December 10, 2017

In the first post in this series, I described how to set-up an account and create a very basic program. I also laid out a timeline for getting a very basic game up and running on an iPhone. In this post, I follow on from here where I describe how to run an application in the simulator.

This time, we’re going to create a different type of project and start the game. In the first post, I described the target of this post to make an object move across the screen; we’re actually going to go slightly further and allow a small amount of control.

Create a new Game Project

This time, when we create a new project, we’ll select “Game”:

xcode mov 1

The next screen is vaguely familiar; for this particular example, we want Swift as the language, and SpriteKit as the game framework:

xcode mov 2

This should create you a new project that looks something like this:

xcode mov 3

It also gives you some code… which causes the program to do this out of the box:

xcode mov 4

Clear Default Game Code

There’s quite a lot of code generated by default in order to create this magnificent application. A lot of it needs deleting; let’s start with the text. In GameScene.sks, select the “Hello, World” text and delete it:

xcode mov 5

Most of the rest of the code is in GameScene.Swift; you can simply clear that; although, unless your target is to create the exact same game as this series of posts describes, you might want to comment out what’s there, so you can revisit later.

Create Object

The first step to making an object move across the screen is to create an object. Our object is going to be a rectangle:

    func createScene(){
        self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
        self.physicsBody?.isDynamic = false
        self.physicsBody?.affectedByGravity = false
        
        //self.physicsWorld.contactDelegate = self
        self.backgroundColor = SKColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
        
        let player = CreatePlayer()
        self.addChild(player)

    }
    
    // Returns SKShapeNode
    func CreatePlayer() -> SKShapeNode {
        
        let playerSize = CGSize(width: 100, height: 50)
        
        let player = SKShapeNode(rectOf: playerSize)
        player.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
        player.strokeColor = SKColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        
        player.physicsBody = SKPhysicsBody(rectangleOf: playerSize)
        
        player.physicsBody?.affectedByGravity = false
        player.physicsBody?.isDynamic = true
            
        return player
    }

There are two functions in the code above. ‘createScene()’ establishes the game environment: background colour, physics rules, etc. This, in turns, calls ‘CreatePlayer()’ and adds the result to ‘self’.

A Quick not on Self

What is ‘self’? As you can see from the class definition, the GameScene class inherits from SKScene:

class GameScene: SKScene {
 

In C# terms, ‘self’ translates to ‘this’, so we’re referring to the instance of a class that inherits from SKScene.

We now have a couple of functions to set the game up, but haven’t yet called them; that’s where the didMove event comes in. This fires after the scene is loaded and rendered:

override func didMove(to view: SKView) {
    createScene()
}

And we have our box:

xcode mov 6

Move Game Object

But the target wasn’t just to draw something on the screen, but to move it. Let’s make it move when you touch the screen. First, we’ll need to declare a couple of variables to hold the player object and the speed they are travelling (BTW, there’s a reason the variable is called playerSpeed and not speed - speed is a variable that exists in the SpriteKit namespace - although you wouldn’t know it from the error!):

class GameScene: SKScene {
    
    private var player : SKShapeNode?
    private var playerSpeed : CGFloat? = 0


There’s a series of events that handle when the user touches the screen, but let’s use ‘touchesBegan’ for now:


    override func touchesBegan(\_ touches: Set<UITouch>, with event: UIEvent?) {
        playerSpeed! += CGFloat(1.0)
    }

Finally, the update function allows the change of game variables before they are rendered:

    override func update(\_ currentTime: TimeInterval) {
        // Called before each frame is rendered
        player?.position.x += playerSpeed!
    }

As far as I can establish, anything inside the SKScene object is automatically rendered each frame by virtue of being there. So, if we were relating this to a C# game engine such as MonoGame, the Draw function is automated.

References

http://sweettutos.com/2017/03/09/build-your-own-flappy-bird-game-with-swift-3-and-spritekit/

https://developer.apple.com/documentation/spritekit/skscene/1519607-didmove

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024