top of page

A simple example of a game coded in Swift using the 2D game framework called SpriteKit

This example demonstrates a basic “Tap the Ball” game, where the user must tap a ball that appears at random locations on the screen. Every tap scores a point.

Step 1: Create a new SpriteKit Game project in Xcode

When creating a new project in Xcode:

​

1. Choose Game under iOS

2. Language: Swift

3. Game Technology: SpriteKit

Step 2: Replace the code in GameScene.swift with the following:

import SpriteKit

class GameScene: SKScene {
    
    var ball: SKShapeNode!
    var scoreLabel: SKLabelNode!
    var score = 0
    
    override func didMove(to view: SKView) {
        backgroundColor = .white
        
        scoreLabel = SKLabelNode(text: "Score: 0")
        scoreLabel.fontSize = 40
        scoreLabel.fontColor = .black
        scoreLabel.position = CGPoint(x: frame.midX, y: frame.height - 80)
        addChild(scoreLabel)
        
        spawnBall()
    }
    
    func spawnBall() {
        ball = SKShapeNode(circleOfRadius: 40)
        ball.fillColor = .systemBlue
        ball.strokeColor = .clear
        ball.name = "ball"
        ball.position = CGPoint(
            x: CGFloat.random(in: 60...(size.width - 60)),
            y: CGFloat.random(in: 100...(size.height - 100))
        )
        addChild(ball)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        let tappedNode = atPoint(location)
        
        if tappedNode.name == "ball" {
            score += 1
            scoreLabel.text = "Score: \(score)"
            ball.removeFromParent()
            spawnBall()
        }
    }
}

 

Step 3: Run the project in the simulator or on a device

You'll see a blue ball appear randomly on the screen. Each time you tap it, it moves somewhere else and your score increases.

bottom of page