Justin Justin - 1 month ago 9
Swift Question

Where can I write code that runs constantly?

In my SpriteKit game, I've been declaring some variables and other things (like SKTextures) first-thing in the GameScene (as class-level variables). However, I want to constantly check for whether a sprite's position is in a specific area.

Is there a specific method that's always being called? Or do I have to write the code in a very special place?

Answer

Yes there is a specific method that runs all the time!

It's called update. You can override this in your SKScene subclass like this

override func update(_ currentTime: TimeInterval) {
    // write your code here...
}

Documentation:

Override this to perform per-frame game logic. Called exactly once per frame before any actions are evaluated and any physics are simulated.

Do not call this method directly; it is called exactly once per frame, so long as the scene is presented in a view and is not paused. By default, this method does nothing. Your scene subclass should override this method and perform any necessary updates to the scene.