efe_ertugrul

apple developer

home tech_notes app_store github stackoverflow devto

About Collisions and Contacts


Learn how to set up nodes for collision detection.

Overview

SpriteKit supports two kinds of interaction between physics bodies that come into contact or attempt to occupy the same space:

Interaction Limits

Your game configures the physics bodies in the scene to determine when collisions should occur and when interactions between physics bodies require additional game logic to be performed. Limiting these interactions is not only important for defining your game’s logic, it is also necessary in order to get good performance from SpriteKit.

SpriteKit uses two mechanisms to limit the number of interactions in each frame:

The following code creates a red and a blue ball, and a ground object constructed from a series of points. By giving the red ball a collisionBitMask that matches the ground’s categoryBitMask, you make the red ball bounce off the ground. However, the blue ball’s collisionBitMask is set to a different value and doesn’t interact with the ground.

let ballRadius: CGFloat = 20
let redBall = SKShapeNode(circleOfRadius: ballRadius)
redBall.fillColor = .red
redBall.position = CGPoint(x: 280, y: 320)
redBall.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)

let blueBall = SKShapeNode(circleOfRadius: ballRadius)
blueBall.fillColor = .blue
blueBall.position = CGPoint(x: 360, y: 320)
blueBall.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)

var splinePoints = [CGPoint(x: 0, y: 300),
                    CGPoint(x: 100, y: 50),
                    CGPoint(x: 400, y: 110),
                    CGPoint(x: 640, y: 20)]
let ground = SKShapeNode(splinePoints: &splinePoints,
                         count: splinePoints.count)
ground.physicsBody = SKPhysicsBody(edgeChainFrom: ground.path!)
ground.physicsBody?.restitution = 0.75

redBall.physicsBody?.collisionBitMask = 0b0001
blueBall.physicsBody?.collisionBitMask = 0b0010
ground.physicsBody?.categoryBitMask = 0b0001

The following image shows the paths taken by both balls when the code above is executed.

073-skphysicsbody-about-collisions-and-contacts-001


download this page as .md

download this page as .pdf

back to SpriteKit documentation