Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In case it helps anyone, a SpriteKit starter with physics turned on and a couple of sprites demonstrating collision detection
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var box1: SKShapeNode?
var box2: SKShapeNode?
override func didMove(to view: SKView) {
let b1 = SKShapeNode(circleOfRadius: 50.0)
let b2 = SKShapeNode(rect: CGRect(x: -50, y: -50, width: 100, height: 100))
b1.fillColor = .yellow
b2.fillColor = .green
let p1 = SKPhysicsBody(circleOfRadius: 50.0)
let p2 = SKPhysicsBody(rectangleOf: CGSize(width: 100, height: 100))
p1.isDynamic = true
p2.isDynamic = false
p1.categoryBitMask = 1
p1.collisionBitMask = 1
p1.contactTestBitMask = 1
p2.categoryBitMask = 1
p2.collisionBitMask = 1
p2.contactTestBitMask = 1
self.addChild(b1)
self.addChild(b2)
b1.position = CGPoint(x: 0.0, y: 300.0)
b1.physicsBody = p1
b2.position = CGPoint(x: 0.0, y: -250)
b2.physicsBody = p2
self.box1 = b1
self.box2 = b2
guard let scene = self.scene else {
preconditionFailure("This should never happen")
}
scene.physicsWorld.gravity = CGVector(dx: 0, dy: -1)
scene.physicsWorld.contactDelegate = self
let boundary =
SKPhysicsBody(edgeLoopFrom: CGRect(x: -400, y: -300, width: 800, height: 600))
boundary.isDynamic = false
boundary.contactTestBitMask = 0
boundary.categoryBitMask = 0
boundary.collisionBitMask = 0
let boundaryNode = SKNode()
boundaryNode.physicsBody = boundary
self.addChild(boundaryNode)
}
}
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
guard let bodyAPosition = contact.bodyA.node?.position,
let bodyBPosition = contact.bodyB.node?.position else {
fatalError("This should never happen")
}
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyBPosition.x < bodyAPosition.x {
say(body: bodyB, "left")
say(body: bodyA, "right")
} else if bodyBPosition.x > bodyAPosition.x {
say(body: bodyA, "left")
say(body: bodyB, "right")
} else if bodyBPosition.y > bodyAPosition.y {
say(body: bodyA, "top")
say(body: bodyB, "bottom")
} else {
say(body: bodyA, "bottom")
say(body: bodyB, "top")
}
}
}
extension GameScene {
func say(body: SKPhysicsBody, _ sayWhat: String) {
guard let node = body.node else {
fatalError("Should never happen")
}
let label = SKLabelNode(text: sayWhat)
label.fontSize *= 0.75
label.fontName = "Courier New"
label.fontColor = .black
node.addChild(label)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment