Sprite Kit Physics Tutorial

Sprite Kit contains a physics edge to make objects move in a realistic way. To enable the movement of the Sprite, a physics body needs to be created. This is a boundary that is used for collision detection. In this tutorial a number of balls will fall down and will fill up the screen in a realistic way. This tutorial is made for iOS9 and created in Xcode 7.

Open Xcode and create a new Project. Choose iOS->Application->Game. 

For product name, use SpriteKitPhysicsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure SpriteKit is selected as Game Technology and only iPhone is selected in Devices.

Download the ball image and add it to the project. Select File -> Add Files to "...". Go to the GameScene.swift file and delete the touchesBegan method since it's not needed for this project. The didMoveToView will be called when the scene is presented to the view. Change this method to

override func didMoveToView(view: SKView) {
    self.backgroundColor = UIColor.whiteColor()
    scene!.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
            count: 200))

The SKPhysicsBody object adds physic simulation to the scene. The edgeLoopFromRect initialiser  adds boundary to the scene, so the balls will not fall through the ground. A sequence of  Sprite Kit Actions is then executed, which will create 200 balls with a delay of 0.05 seconds. In the sequence the createBall method is called, so let's implement this method

func createBall() {
     let ball: SKSpriteNode = SKSpriteNode(imageNamed: "black")
     ball.position = CGPoint(
         x: CGFloat(Int(arc4random()) % Int(self.size.width)),
         y: self.size.height - ball.size.height)
     ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)

A sprite is created from the ball image and it is positioned at the top of the window at a random x-coordinate. The circleOfRadius method creates a circled physics body on the ball sprite. Build and Run the Project, the balls will fall down and stack on top of each other.

You can download the source code of the SpriteKitPhysicsTutorial at the ioscreator repository on github.