I am trying to make my game restart when two objects colliding. I tried coding it so it does that. I used print statements as placeholders just to see if its working correctly. They print when the two objects collide so I decided to replace it with code to change the position of the ball when they collide, it doesn't work now. I also tried creating a function to start the game over, that also doesn't work.
func didBegin(_ contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if contactMask == PhysicsCategories.ballCategory | PhysicsCategories.dangerCategory {
startGame()
} else if contactMask == PhysicsCategories.ballCategory | PhysicsCategories.goalCategory {
print("goal contact")
}
}
Main Code:
override func didMove(to view: SKView) {
ball = self.childNode(withName: "ball") as! SKSpriteNode
danger1 = self.childNode(withName: "danger1") as! SKSpriteNode
danger2 = self.childNode(withName: "danger2") as! SKSpriteNode
goal = self.childNode(withName: "goal") as! SKSpriteNode
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 0
danger1.physicsBody = SKPhysicsBody(rectangleOf: danger1.size)
danger1.physicsBody?.categoryBitMask = PhysicsCategories.dangerCategory
danger2.physicsBody = SKPhysicsBody(rectangleOf: danger2.size)
danger2.physicsBody?.categoryBitMask = PhysicsCategories.dangerCategory
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.categoryBitMask = PhysicsCategories.ballCategory
ball.physicsBody?.contactTestBitMask = PhysicsCategories.dangerCategory
ball.physicsBody?.collisionBitMask = PhysicsCategories.none
goal.physicsBody = SKPhysicsBody(rectangleOf: goal.size)
goal.physicsBody?.categoryBitMask = PhysicsCategories.goalCategory
danger1.physicsBody?.isDynamic = false
ball.physicsBody?.isDynamic = true
goal.physicsBody?.isDynamic = false
danger2.physicsBody?.isDynamic = false
danger2.physicsBody!.affectedByGravity = false
danger1.physicsBody!.affectedByGravity = false
goal.physicsBody!.affectedByGravity = false
ball.physicsBody!.affectedByGravity = false
setupPhysics()
startGame()
}
settings.swift:
import SpriteKit
enum PhysicsCategories {
static let none: UInt32 = 0
static let ballCategory: UInt32 = 0x1 // 01
static let dangerCategory: UInt32 = 0x1 << 1 // 10
static let goalCategory: UInt32 = 0x1 << 2
}
Comments
Post a Comment