Justin Justin - 29 days ago 9
Swift Question

Where Do I Write Generic Code in Swift3 > Sprite Kit?

thanks for your time! Super quick question for all you pros:

In my compiler, I've been declaring some variables and other things (like SKTextures) first-thing in the GameScene, outside any methods. However, typing generic code such as stating "If my sprite's position is in this area, do this" doesn't seem to work there... I don't want to put it in a method because I don't want it to get called/checked only when, say, the user is touching the screen.

Or is there a specific method that's always running?? ViewDidLoad only happens at the very start, correct?

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.

Comments