Sprite Kit Physics iOS Tutorial

The Sprite Kit framework contains a SKPhysicsBody object to add physics simulation. In this tutorial a number of balls will fall down and will fill up the screen in a realistic way. The edge of the screen will be used as an physical boundary so the balls will not fall through. This tutorial is made with Xcode 10 and built for iOS 12.

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

For product name, use IOSSpriteKitPhysicsTutorial 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.

Go to the GameScene.sks file and delete the hello World label. Select the Scene and in the Attributes inspector change the X and Y values of the Anchor point to 0.

Download the ball image. Open the Assets folder from the project and drag the ball image here. The Game template added some code to the project we will not need. Go to the GameScene.swift file and delete all code inside the GameScene class. Add the didMove(to:) method

override func didMove(to view: SKView) {
    backgroundColor = UIColor.white

    scene!.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    run(SKAction.repeat(SKAction.sequence([SKAction.run(createBall), SKAction.wait(forDuration: 0.05)]), count: 200))

The SKPhysicsBody object adds physic simulation to the scene. The edgeLoopFromRect initializer  adds a 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(imageNamed: "ball")
    ball.position = CGPoint(x: CGFloat(Int(arc4random()) & Int(size.width)),
                            y: 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 IOSSpriteKitPhysicsTutorial at the ioscreator repository on github.