Add a Physics Contact Extension

Apple Game Frameworks and Technologies — by Tammy Coron (117 / 193)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Configure the Physics Bodies | TOC | Place Collectibles and Doors 👉

Inside the Extensions group, create a new file (⌘N) using the iOS Swift File template. Name the new file GameScene+PhysicsContact.swift and replace its contents with the following:

​ ​import​ ​SpriteKit​

​ ​extension​ ​GameScene​: ​SKPhysicsContactDelegate​ {
​ ​func​ ​didBegin​(_ contact: ​SKPhysicsContact​) {
​ ​let​ collision = contact.bodyA.categoryBitMask
​ | contact.bodyB.categoryBitMask

​ ​switch​ collision {
​ ​default​:
​ ​break​
​ }
​ }
​ }

This code is the start of your physics contact manager.

To keep the code organized and make it easier to see what contacts are taking place, you’ll use code comments. Add the following code just above the line that reads default::

​   ​// MARK: -  Player | Collectible​

​ ​case​ ​PhysicsBody​.player.categoryBitMask |
​ ​PhysicsBody​.collectible.categoryBitMask:
​ ​let​ playerNode = contact.bodyA.categoryBitMask ==
​ ​PhysicsBody​.player.categoryBitMask ?
​ contact.bodyA.node : contact.bodyB.node

​ ​let​ collectibleNode = contact.bodyA.categoryBitMask ==
​ ​PhysicsBody​.collectible.categoryBitMask ?
​ contact.bodyA.node : contact.bodyB.node

​ ​// TODO: ADD CODE TO HANDLE PLAYER COLLECTION​

​ ​// MARK: - Player | Door​

​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.