NEW! Master Swift design patterns with my latest book! >>

How to add physics to an SKSpriteNode

Paul Hudson       @twostraws

SpriteKit comes with a modified version of the Box2D physics framework, and it's wrapped up a lot of complicated physics mathematics into just one or two lines of code. For example, we can create a square, red sprite and give it rectangular physics like this:

let box = SKSpriteNode(color: UIColor.red, size: CGSize(width: 64, height: 64))
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 64, height: 64))

That rectangle will wrap perfectly around the box's color, so it will bounce and rotate as it collides with other objects in your scene.

If you want to create circular physics to simulate balls, this is done using the circleOfRadius constructor:

let ball = SKSpriteNode(imageNamed: "ballRed")
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)

Available from iOS 7.0 – see Hacking with Swift tutorial 11

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

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

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>