GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

How to simulate gravity in a SpriteKit scene

Swift version: 5.10

Paul Hudson    @twostraws   

Once you’ve given all your SpriteKit nodes physics bodies, you might want to add some simulated gravity so they fall to the ground over time. This technique is also useful if you want to simulate wind (think of it like horizontal gravity), or even for making the user tilt their device to make nodes fall in different directions.

Gravity for your scene is configured using the physicsWorld.gravity property. By default it’s set to a value equal to Earth’s gravity of 9.8 meters per second, but you can change that however you want. For example, you might want to simulate someone walking on the moon where gravity is 1.62 meters per second:

physicsWorld.gravity = CGVector(dx: 0, dy: -1.62)

Alternatively you can disable gravity entirely by using a zero vector:

physicsWorld.gravity = .zero

These changes don’t need to be permanent – you could disable gravity when the player picks up an anti-grav belt, then re-enable it after 30 seconds.

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0 – learn more in my book Dive Into SpriteKit

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.