[Solved] Check if the player has hit a margin


Use SpriteKit. You can select this when creating a new project, choose Game, and then select SpriteKit. It’s Apple’s framework to make games. It has what you will need, and is also faster – don’t make games in UIKit.

New game project

Within SpriteKit, you have the update() method, as part of SKScene. Do NOT use a while loop. These are highly unreliable, and the speed of the snake will vary between devices.

SKScene update loop

Here is a small piece of code to help you get started on the SKScene:

import SpriteKit


class Scene: SKScene {

    let timeDifference: TimeInterval = 0.5  // The snake will move 2 times per second (1 / timeDifference)
    var lastTime: TimeInterval = 0

    let snakeNode = SKSpriteNode(color: .green, size: CGSize(width: 20, height: 20))


    override func update(_ currentTime: TimeInterval) {
        if currentTime > lastTime + timeDifference {
            lastTime = currentTime

            // Move snake node (use an SKSpriteNode or SKShapeNode)
        }
    }
}

After doing all this, you can finally check if the snake is over some margins or whatever within this update() loop. Try to reduce the code within the update() loop as much as possible, as it gets run usually at 60 times per second.

3

solved Check if the player has hit a margin