SpriteKit Collision Detection Not Working Properly - ios

I have three nodes in my game-
The Player -
This is a boat that you drag around using a joystick.
let collisionPlayer : UInt32 = 0x1 << 1
let apple = SKSpriteNode(texture: texture)
apple.position = position
apple.physicsBody = SKPhysicsBody(circleOfRadius: apple.size.width / 2.0)
apple.physicsBody?.affectedByGravity = false
apple.physicsBody?.isDynamic = true
apple.setScale(0.1)
addChild(apple)
("apple" is the boat)
The Enemy Boat -
This is a CPU boat that randomly follows the player around.
let collisionNPC : UInt32 = 0x1 << 0
appleNPC.position = position
appleNPC.physicsBody = SKPhysicsBody(circleOfRadius: appleNPC.size.width / 2.0)
appleNPC.physicsBody?.isDynamic = true
appleNPC.physicsBody?.affectedByGravity = false
appleNPC.position = CGPoint(x: 600, y: 200)
appleNPC.setScale(0.1)
addChild(appleNPC)
The Bullet
(self-explanatory)
let collisionBullet : UInt32 = 0x1 << 2
(The following code is in TouchesEnded)
bullet?.name = "Bullet"
bullet?.position = (appleNode?.position)!
bullet?.setScale(0.05)
bullet?.zPosition = 1
bullet?.physicsBody = SKPhysicsBody(circleOfRadius: (bullet?.size.width)!/2)
bullet?.physicsBody?.isDynamic = true
bullet?.physicsBody?.affectedByGravity = false
bullet?.physicsBody?.usesPreciseCollisionDetection = true
To move the bullet I use the code:
// Your code with delay
if bulletNumbers > 0 {
let offset = CGPoint(x: touchLocation.x - (bullet?.position.x)! , y: touchLocation.y - (bullet?.position.y)!)
//Stops Bullet from shooting backwards
//Get the direction of where to shoot
let direction = offset
//Make it shoot far enough to be guaranteed off screen
let shootAmount = CGPoint(x: direction.x * 10, y: direction.y * 10)
//Add the shoot amount to the current position
let realDest = CGPoint(x: shootAmount.x + (bullet?.position.x)!, y: shootAmount.y + (bullet?.position.y)!)
//Create the actions
addChild(bullet!)
self.bulletNumbers -= 1
let distance = sqrt(pow(realDest.x - (appleNode?.position.x)!, 2) +
pow(realDest.y - (appleNode?.position.y)!, 2))
// run the sequence of actions for the firing
let duration = TimeInterval(distance / PlayerMissileSpeed)
let missileMoveAction = SKAction.move(to: realDest, duration: duration)
let when = DispatchTime.now() + 10 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) { self.bulletNumbers += 1
}
bullet?.run(missileMoveAction) {
self.bullet?.isHidden = true
self.bullet?.removeFromParent()
print("\(self.bulletNumbers)")
}}
else if bulletNumbers <= 0 {
print("reload")
let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
}
}
}
func didBegin(_ contact: SKPhysicsContact) {
print("test")
}
func setRandomStickColor() {
let randomColor = UIColor.random()
moveAnalogStick.stick.color = randomColor
}
func setRandomSubstrateColor() {
let randomColor = UIColor.random()
moveAnalogStick.substrate.color = randomColor
}
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
super.update(currentTime)
let _:UInt32 = arc4random_uniform(1) //
appleNodeCpuSpeed = CGFloat(1)
var locationx : CGFloat
var locationy: CGFloat
locationx = (appleNode?.position.x)!
locationy = (appleNode?.position.y)!
let dx = locationx - (appleNodeNPC?.position.x)!
let dy = locationy - (appleNodeNPC?.position.y)!
let angle = atan2(dy, dx)
let vx = cos(angle) * appleNodeCpuSpeed
let vy = sin(angle) * appleNodeCpuSpeed
self.appleNodeNPC?.position.x += vx
self.appleNodeNPC?.position.y += vy
let when = DispatchTime.now() + 0.25 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
self.appleNodeNPC?.zRotation = angle + 90
}
//2
This works fine. The bullet is launched from the boat to the touch location, however, things start to go wrong when I tried to introduce collisions. Here is my code below:
appleNode?.physicsBody?.categoryBitMask = collisionPlayer
appleNode?.physicsBody?.collisionBitMask = collisionNPC
appleNode?.physicsBody?.contactTestBitMask = 0
appleNodeNPC?.physicsBody?.categoryBitMask = collisionNPC
appleNodeNPC?.physicsBody?.collisionBitMask = collisionPlayer
appleNodeNPC?.physicsBody?.contactTestBitMask = collisionBullet
bullet?.physicsBody?.categoryBitMask = collisionBullet
bullet?.physicsBody?.collisionBitMask = 0
bullet?.physicsBody?.contactTestBitMask = collisionNPC
physicsWorld.contactDelegate = self
view.showsPhysics = true
Then in my didBegin function I have:
func didBegin(_ contact: SKPhysicsContact) {
print("test")
}
Let's start from the beginning. I tap the screen and the bullet is launched. The bullet does not collide with the Player, which is what I originally wanted. However, when the bullet makes contact with the Enemy ship it DOES collide. It goes around the ship and keeps going on to its original destination. I want the bullet to contact the ship and nothing else - no collisions. I would hope to assume that my error here is because of my code for moving the bullet, but i'm not sure. Any help is appreciated.

Define unique categories, ensure your class is a SKPhysicsContactDelegate and make yourself the physics contact delegate:
//Physics categories
let appleCategory: UInt32 = 1 << 0
let enemyCategory: UInt32 = 1 << 1
let bulletCategory: UInt32 = 1 << 2
class GameScene: SKScene, SKPhysicsContactDelegate {
physicsWorld.contactDelegate = self
Assign the categories (usually in didMove(to view:) :
apple.physicsBody.catgeoryBitMask = appleCategory
enemy.physicsBody.catgeoryBitMask = enemyCategory
bullet.physicsBody.catgeoryBitMask = bulletCategory
(Make sure you've created physics bodies for each node)
Set up collisions:
apple.physicsBody?.collisionBitMask = 0 // apple/player collides with nothing
enemy.physicsBody?.collisionBitMask = 0 // enemy collides with nothing
bullet.physicsBody?.collisionBitMask = 0 // bullet collides with nothing
or even:
for node in [apple, enemy, bullet] {
node.physicsBody?.collisionBitMask = 0 // collides with nothing
}
Set up contacts
bullet.physicsBody?.collisionBitMask = enemyCategory // bullet contacts enemy
Make sure that at least one of the objects involved in each potential contact has the isDynamic property on its physics body set to true, or no contact will be generated. It is not necessary for both of the objects to be dynamic.
You should now get didBegin called when the bullet and the enemy make contact. You could code didBegin like this:
func didBegin(_ contact: SKPhysicsContact) {
print("didBeginContact entered for \(String(describing: contact.bodyA.node!.name)) and \(String(describing: contact.bodyB.node!.name))")
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case bulletCategory | enemyCategory:
print("bullet and enemy have contacted.")
let bulletNode = contact.bodyA.categoryBitMask == bulletCategory ? contact.bodyA.node : contact.bodyB.node
enemyHealth -= 10
bulletNode.removeFromParent
default:
print("Some other contact occurred")
}
}

Related

Spritekit Detecting Sprite Overlap with Collisions off

Currently I have a Swift/Spritekit app that drops a sprite from the sky, they have collisions off so they can fall through the floor, however I am trying to make a statement that will detect when the player sprite touches the sprite falling from the sky then deletes that child and adds a point to the score var.
Update: 04/29/18 2:10 CST
As of now this is what I have
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var activePlayer:SKSpriteNode! = SKSpriteNode() //Sets active character
var bg:SKSpriteNode! = SKSpriteNode()
var bananaCollected = 0 //Defines banana var
var timer: Timer?
let bananaCat : UInt32 = 0x1 << 1
let playerCat : UInt32 = 0x1 << 2
func bananaDrop() { //Defines bananaDrop
let banana = SKSpriteNode(imageNamed:"banana")
//print("- Debug: [bananaDrop] successfully initiated -")
banana.name = "banana"
//Size of banana
banana.xScale = 0.25
banana.yScale = 0.25
//Defines physics properties
let physicsBody = SKPhysicsBody(circleOfRadius: 15)
//let physicsBody = SKPhysicsBody()
//physicsBody.pinned = true //Suspend in air
physicsBody.allowsRotation = false
physicsBody.affectedByGravity = true
//physicsBody.collisionBitMask = 0
banana.physicsBody?.categoryBitMask = bananaCat
banana.physicsBody?.collisionBitMask = 0
banana.physicsBody?.contactTestBitMask = playerCat
//categoryBitMask is what the physics category of the object is
//banana.physicsBody!.categoryBitMask = playerCategory
//collisionBitMask is what the physics category of objects that this cannot pass through are...multiple categories would be typed like... `cat1 | cat2`
//banana.physicsBody!.collisionBitMask = 0
//contactTestBitMask is what the physics category of the objects that we get alerted to upon contact
//activePlayer.physicsBody!.contactTestBitMask = obstacleCategory
banana.physicsBody = physicsBody
//Starting Location Defined
var x: CGFloat = 0 //Defines X
let y: CGFloat = 400 //Defines how high up banana drops
let bananaDrop = GKShuffledDistribution(lowestValue: 1, highestValue: 11)
//Drop locations defined (relation to X)
switch bananaDrop.nextInt() {
case 1:
x = -170
case 2:
x = -160
case 3:
x = -120
case 4:
x = -80
case 5:
x = -40
case 6:
x = 0
case 7:
x = 40
case 8:
x = 80
case 9:
x = 120
case 10:
x = 160
case 11:
x = 170
default:
fatalError("Case num outside range")
}
banana.position = CGPoint(x: x, y: y)
//Adds banana
self.addChild(banana)
}
func bDropF() { //Defintes Banana Drop Final
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] timer in
self?.timer = timer
self?.timerTime()
})
}
//Stop droping bananas
deinit {
self.timer?.invalidate()
}
func timerTime() {
bananaDrop()
}
override func didMove(to view: SKView) {
print("- Debug: Game Scene Loaded -")
bDropF() //Calls banana drop
if let setupBG:SKSpriteNode = self.childNode(withName: "bg") as? SKSpriteNode {
bg = setupBG
bg.name = "bg"
bg.physicsBody?.affectedByGravity = false
bg.zPosition = -1
}
func didBeginContact(_ contact: SKPhysicsContact){ //Banana Collect
if let firstNode = contact.bodyA.node as? SKSpriteNode, let secondNode = contact.bodyB.node as? SKSpriteNode {
let object1: String = firstNode.name!
let object2: String = secondNode.name!
if (object1 == "player") || (object2 == "banana") {
print("colliding!")
}
}
}
//Player Definitions
if let randoPlayer:SKSpriteNode = self.childNode(withName: "player") as? SKSpriteNode { //Test for Char type
activePlayer = randoPlayer //Char Set
activePlayer.physicsBody?.isDynamic = true //Set dynamic
activePlayer.physicsBody?.affectedByGravity = true //Set dynamic gravity
activePlayer.name = "player"
print("Player Initiated")
print("Physics set :: Dynamic(true):AffectedByGravity(true)")
} else {
print("Failed to initiate player")
}
}
func moveActivePlayerR() {//Right Touch Player Movements Defined
let walkAnimation:SKAction = SKAction(named: "WalkRight")!
let moveAction:SKAction = SKAction.moveBy(x: 100, y: 0, duration: 0.5) //Move Right Side
//let moveRight:SKAction = SKAction.group([walkAnimation, moveAction]) //Depricated
let sound = SKAction.playSoundFileNamed("walk.wav", waitForCompletion: false)
let finalWalkR:SKAction = SKAction.group([walkAnimation, moveAction, sound])
activePlayer.run(finalWalkR)
}
func moveActivePlayerL() { //Left Touch Player Movements Defined
let walkAnimation:SKAction = SKAction(named: "WalkLeft")!
let moveAction:SKAction = SKAction.moveBy(x: -100, y: 0, duration: 0.5) //Move Left Side
//let moveRight:SKAction = SKAction.group([walkAnimation, moveAction]) //Depricated
let sound = SKAction.playSoundFileNamed("walk.wav", waitForCompletion: false)
let finalWalkL:SKAction = SKAction.group([moveAction, sound, walkAnimation])
activePlayer.run(finalWalkL)
}
func touchDown(atPoint pos : CGPoint) {
print("touch \( pos.x),\(pos.y)") //Debug print
if(pos.x > 0) { //if touched right side of screen
print("Right touch")
moveActivePlayerR()
} else if (pos.x < 0) { //if touched left side of screen
print("Left touch")
moveActivePlayerL()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
self.touchDown(atPoint: t.location(in: self))
}
}
}
However even with these categories setup it still appears that I am unable to get them to collide properly. When they touch each other there is nothing in my console indicating that they have collided. Please help!
You do not have to have a collisionBitMask set in order to detect contact, you just need to set the contactTestBitMask to the category of the obstacle you want to detect the collision with. You then check for the collision in the didBegin func. Ensure that you have the SKPhysicsContactDelegate set on your scene.
class GameScene: SKScene, SKPhysicsContactDelegate
self.physicsWorld.contactDelegate = self
when setting up your objects
//categoryBitMask is what the physics category of the object is
object.physicsBody!.categoryBitMask = playerCategory
//collisionBitMask is what the physics category of objects that this cannot pass through are...multiple categories would be typed like... `cat1 | cat2`
object.physicsBody!.collisionBitMask = 0
//contactTestBitMask is what the physics category of the objects that we get alerted to upon contact
object.physicsBody!.contactTestBitMask = obstacleCategory
the didBegin func in your scene
func didBeginContact(_ contact: SKPhysicsContact) {
if let firstNode = contact.bodyA.node as? SKSpriteNode, let secondNode = contact.bodyB.node as? SKSpriteNode {
let object1: String = firstNode.name!
let object2: String = secondNode.name!
if (object1 == "obstacle") || (object2 == "obstacle") {
//run some code because these 2 have collided
}
}
}
...or...
func didBeginContact(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == PhysicsCategory.obstacleCategory || contact.bodyB.categoryBitMask == PhysicsCategory.obstacleCategory {
//obstacle has hit player do something
}
}

Need objects to move with a constant speed

I'm trying to create a game, where the objects need to chase food. Right now the objects speeds up, when the food is within the given radius. But I need the speed to always be the same.
Any suggestions how to fix this? I have tried to add an SKAction under the chase function, where I set the position.x and position.y, but I can't make it work correct.
Fish class:
class Fish:SKSpriteNode{
private let kMovingAroundKey = "movingAround"
private let kFishSpeed:CGFloat = 4.5
private var swimmingSpeed:CGFloat = 100.0
private let sensorRadius:CGFloat = 100.0
private weak var food:SKSpriteNode! = nil //the food node that this fish currently chase
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
physicsBody = SKPhysicsBody(rectangleOf: size)
physicsBody?.affectedByGravity = false
physicsBody?.categoryBitMask = Collider.fish
physicsBody?.contactTestBitMask = Collider.food
physicsBody?.collisionBitMask = 0x0 //No collisions with fish, only contact detection
name = "fish"
let sensor = SKShapeNode(circleOfRadius: 100)
sensor.fillColor = .red
sensor.zPosition = -1
sensor.alpha = 0.1
addChild(sensor)
}
func getDistanceFromFood()->CGFloat? {
if let food = self.food {
return self.position.distance(point: food.position)
}
return nil
}
func lock(food:SKSpriteNode){
//We are chasing a food node at the moment
if let currentDistanceFromFood = self.getDistanceFromFood() {
if (currentDistanceFromFood > self.position.distance(point: food.position)){
//chase the closer food node
self.food = food
self.stopMovingAround()
}//else, continue chasing the last locked food node
//We are not chasing the food node at the moment
}else{
//go and chase then
if food.position.distance(point: self.position) <= self.sensorRadius {
self.food = food
self.stopMovingAround()
}
}
}
//Helper method. Not used currently. You can use this method to prevent chasing another (say closer) food while already chasing one
func isChasing(food:SKSpriteNode)->Bool{
if self.food != nil {
if self.food == food {
return true
}
}
return false
}
func stopMovingAround(){
if self.action(forKey: kMovingAroundKey) != nil{
removeAction(forKey: kMovingAroundKey)
}
}
//MARK: Chasing the food
//This method is called many times in a second
func chase(within rect:CGRect){
guard let food = self.food else {
if action(forKey: kMovingAroundKey) == nil {
self.moveAround(within: rect)
}
return
}
//Check if food is in the water
if rect.contains(food.frame.origin) {
//Take a detailed look in my Stackoverflow answer of how chasing works : https://stackoverflow.com/a/36235426
let dx = food.position.x - self.position.x
let dy = food.position.y - self.position.y
let angle = atan2(dy, dx)
let vx = cos(angle) * kFishSpeed
let vy = sin(angle) * kFishSpeed
position.x += vx
position.y += vy
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveAround(within rect:CGRect){
if scene != nil {
//Go randomly around the screen within view bounds
let point = rect.randomPoint()
//Formula: time = distance / speed
let duration = TimeInterval(point.distance(point: position) / self.swimmingSpeed)
let move = SKAction.move(to: point, duration: duration)
let block = SKAction.run {
[unowned self] in
self.moveAround(within: rect)
}
let loop = SKAction.sequence([move,block])
run(loop, withKey: kMovingAroundKey)
}
}
}
Gamescene where you can see the update function.
override func update(_ currentTime: TimeInterval) {
self.enumerateChildNodes(withName: "fish") {
[unowned self] node, stop in
if let fish = node as? Fish {
self.enumerateChildNodes(withName: "food") {
node, stop in
fish.lock(food: node as! SKSpriteNode)
}
fish.chase(within: self.water.frame)
}
}
}
Probably something like this (GameScene):
var prev : TimeInterval!
//MARK: Chasing the food
override func update(_ currentTime: TimeInterval) {
defer { prev = currentTime }
guard prev != nil else { return }
let dt = currentTime - prev
print("delta time \(dt)")
self.enumerateChildNodes(withName: "fish") {
[unowned self] node, stop in
if let fish = node as? Fish {
self.enumerateChildNodes(withName: "food") {
node, stop in
fish.lock(food: node as! SKSpriteNode)
}
fish.chase(within: self.water.frame, delta:CGFloat(dt))
}
}
}
The variable prev is a property of GameScene.
And change chase() method in Fish class:
//MARK: Chasing the food
func chase(within rect:CGRect, delta:CGFloat){
guard let food = self.food else {
if action(forKey: kMovingAroundKey) == nil {
self.moveAround(within: rect)
}
return
}
//Check if food is in the water
if rect.contains(food.frame.origin) {
//Take a detailed look in my Stackoverflow answer of how chasing works : https://stackoverflow.com/a/36235426
//check for collision
if self.frame.contains(food.frame.origin) {
food.removeFromParent()
}else {
let dx = food.position.x - self.position.x
let dy = food.position.y - self.position.y
let angle = atan2(dy, dx)
let vx = cos(angle) * self.swimmingSpeed * delta
let vy = sin(angle) * self.swimmingSpeed * delta
print("vx \(vx), vy (\(vy)")
position.x += vx
position.y += vy
//time = distance / speed
}
}
}
I have added the delta time parameter. You may wonder what is delta time? I will quote LearnCocos2d from that article:
Delta time is simply the time difference between the previous and the
current frame.
Why is this important to maintain the constant speed of a node? Well, we use our Fish.swimmingSpeed variable to determine the speed of fish(forget kFishSpeed, it doesn't have a purpose now).
Now in the case of SKAction, a duration parameter directly determines the speed of fish, because duration applies to time, and time = distance / speed, so we calculate the time like this currently:
let duration = TimeInterval(point.distance(point: position) / self.swimmingSpeed)
Now lets say that duration equals to 1. That means, the fish is going to move 100 pts per second. Now, the difference between update() method and actions, is that it is executed 60 times per second. And because our method chase() is ideally called 60 time per second, our speed now have to be Fish.swimmingSpeed / 60.
And this is where delta time comes in. Because it may happen that frame is not rendered in 1/60 second (0.016667), but rather rendering may take longer (eg. 0.02,0.03 sec), we calculate that difference, and use it to adjust the movement. Kind of cheating IMO in compare to normal behaviour without using delta time, because player loses the control on moments if game lags a lot (eg. its hero teleports), but that part is off topic :) It is up to you to test what works / looks better for you.
So we do (in order to calculate the distance):
let vx = cos(angle) * self.swimmingSpeed * delta
let vy = sin(angle) * self.swimmingSpeed * delta
and that will give you a constant speed.
I could go more into detail but it is late here, and you probably got an idea how things are functioning, so I will stop here. Happy coding!

Collide type source error - spritekit swift game

So I have adjusted my games ball type from a shape to an image which forced me to redo the physics of my game. I am new to swift and have struggled with fixing my collisions in my swift game.
class GameScene: SKScene, GameDelegate, SKPhysicsContactDelegate {
var ball: Ball!
let ballSpeedX = CGFloat(500)
//ball = Ball(imageNamed:"colorBall.png")
enum CollisionTypes: UInt32 {
case Floor = 1
case Ball = 2
}
// board
let boards = Boards.make(CollideType.BoardStart.rawValue)
var lastBoard: SKNode?
var boardSpeedY: CGFloat { get { return CGFloat(160) * accelerate }}
let boardDistanceY = CGFloat(300)
let boardYDistanceHide = CGFloat(30)
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsWorld.contactDelegate = self
let flooeBody = SKPhysicsBody.init(edgeLoopFromRect: self.frame)
self.physicsBody = floorBody
self.physicsBody!.affectedByGravity = false
self.physicsBody!.usesPreciseCollisionDetection = true
self.physicsBody!.dynamic = true
self.physicsBody!.mass = 0
self.physicsBody!.friction = 0
self.physicsBody!.linearDamping = 0
self.physicsBody!.angularDamping = 0
self.physicsBody!.restitution = 1
self.physicsBody!.categoryBitMask = CollisionTypes.Floor.rawValue
self.physicsBody!.contactTestBitMask = CollisionTypes.Ball.rawValue
// Prepare the ball - physics engine.
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
ball.physicsBody!.affectedByGravity = true
ball.physicsBody!.restitution = 0.8
ball.physicsBody!.linearDamping = 0
ball.physicsBody!.friction = 0.3
ball.physicsBody!.dynamic = true
ball.physicsBody!.mass = 0.5
ball.physicsBody!.allowsRotation = true
ball.physicsBody!.categoryBitMask = CollisionTypes.Ball.rawValue
ball.physicsBody!.contactTestBitMask = CollisionTypes.Floor.rawValue
ball.physicsBody!.collisionBitMask = CollisionTypes.Floor.rawValue
ball.hidden = false
self.addChild(ball)
// scene
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody!.categoryBitMask = CollideType.Scene.toMask()
self.physicsBody!.dynamic = false
self.physicsBody!.friction = 0
// ceil
let ceil = SKShapeNode(rectOfSize: CGSize(width: self.frame.width, height: 2))
ceil.position.x = CGRectGetMidX(self.frame)
ceil.position.y = self.frame.height - CGRectGetMidY(ceil.frame)
ceil.physicsBody = SKPhysicsBody(rectangleOfSize: ceil.frame.size)
ceil.physicsBody!.categoryBitMask = CollideType.Ceil.toMask()
ceil.physicsBody!.dynamic = false
ceil.alpha = 0
self.addChild(ceil)
// floor
let floor = SKShapeNode(rectOfSize: CGSize(width: self.frame.width, height: 2))
floor.position.x = CGRectGetMidX(self.frame)
floor.position.y = CGRectGetMidY(floor.frame)
floor.physicsBody = SKPhysicsBody(rectangleOfSize: floor.frame.size)
//floor.physicsBody!.categoryBitMask = CollideType.Floor.toMask() two
floor.physicsBody!.dynamic = false
floor.alpha = 0
self.addChild(floor)
}
That is the scene and physics I attempted to set up and was directed with. Below is the collide errors which cause the app to crash upon touch.
func didBeginContact(contact: SKPhysicsContact) {
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollisionTypes.Floor.rawValue && contact.bodyB.categoryBitMask == CollisionTypes.Ball.rawValue
let ballAndBoardMask = CollideType.Ball.toMask() | boards.usedCollideMasks
// ball and board error: CANNOT CONVERT VALUE OF TYPE BOOL TO EXPCTD ARG TYPE UIINT32
if bitMaskAAndB | ballAndBoardMask == ballAndBoardMask {
let boardNode: SKNode! = contact.bodyA.categoryBitMask == CollideType.Ball.toMask() ? contact.bodyB.node : contact.bodyA.node
let board = boardNode.bind as! BoardDelegate
board.didBeginContact(boardNode, ball: ball, contact: contact, game: self)
}
// ball and ceil => ERROR
else if bitMaskAAndB == CollideType.toMask([.Ball, .Ceil]) {
stopGame()
}
// ball and floor => stop game
else if bitMaskAAndB == CollideType.toMask([.Ball, .Floor]) {
stopGame()
}
}
func didEndContact(contact: SKPhysicsContact) {
let ballAndBoardMask = CollideType.Ball.toMask() | boards.usedCollideMasks
// ball and board, handle it by board delegate
if contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask | ballAndBoardMask == ballAndBoardMask {
let boardNode: SKNode! = contact.bodyA.categoryBitMask == CollideType.Ball.toMask() ? contact.bodyB.node : contact.bodyA.node
let board = boardNode.bind as! BoardDelegate
board.didEndContact(boardNode, ball: ball, contact: contact, game: self)
}
}
CollideType definition as below:
enum CollideType: Int {
case Scene = 0
case Ceil = 1
case Floor = 2
case Ball = 3
case BoardStart = 4
func toMask()-> UInt32 {
return UInt32(1 << self.rawValue)
}
static func toMask(masks: [CollideType])-> UInt32 {
var toMask = UInt32(0)
for type in masks {
toMask |= type.toMask()
}
return toMask
}
So the issue now is that you have two definition for your masks:
Remove this one:
enum CollisionTypes: UInt32 {
case Floor = 1
case Ball = 2
}
Use only this one:
enum CollideType: Int {
case Scene = 0
case Ceil = 1
case Floor = 2
case Ball = 3
case BoardStart = 4
func toMask()-> UInt32 {
return UInt32(1 << self.rawValue)
}
static func toMask(masks: [CollideType])-> UInt32 {
var toMask = UInt32(0)
for type in masks {
toMask |= type.toMask()
}
return toMask
}
Correct all code to match with CollideType definitions.
Correct this line in didBeginContact:
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollisionTypes.Floor.rawValue && contact.bodyB.categoryBitMask == CollisionTypes.Ball.rawValue
with:
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollideType.Floor.toMask() ? contact.bodyB.categoryBitMask : CollideType.Ball.toMask()
If you have correct all you will don't have yet this error:
// ball and ceil => ERROR

Collect coins and add to score label in Sprite Kit

I'm trying to implement a simple scoring system into my game using this tutorial as a reference:
http://www.raywenderlich.com/87232/make-game-like-mega-jump-sprite-kit-swift-part-2
The problem is, if I try to implement as is, it crashes in the GameScene.swift on this line:
let another = whichNode as! GameObjectNode
Here are the main parts of the code where the player collects the coins. I can also invite you to my repo if you'd like to take a closer and better look. I know it can be hard from looking at the code I pasted up here.
GameObjectNode.swift:
enum CoinType: Int {
case Normal = 0
case Special
}
struct CollisionCategoryBitmask {
static let Player: UInt32 = 0x00
static let Coin: UInt32 = 0x01
static let Platform: UInt32 = 0x02
}
class GameObjectNode: SKNode {
func collisionWithPlayer(player: SKNode) -> Bool {
return false
}
func checkNodeRemoval(playerY: CGFloat) {
if playerY > self.position.y + 300.0 {
self.removeFromParent()
}
}
}
class CoinNode: GameObjectNode {
let coinSound = SKAction.playSoundFileNamed("StarPing.wav", waitForCompletion: false)
var coinType: CoinType!
override func collisionWithPlayer(player: SKNode) -> Bool {
// Boost the player up
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 400.0)
// Play sound
runAction(coinSound, completion: {
// Remove this Star
self.removeFromParent()
})
// Award score
GameState.sharedInstance.score += (coinType == .Normal ? 20 : 100)
// Award stars
GameState.sharedInstance.coins += (coinType == .Normal ? 1 : 5)
// The HUD needs updating to show the new stars and score
return true
}
}
GameState.swift
class GameState {
var score: Int
var highScore: Int
var coins: Int
init() {
// Init
score = 0
highScore = 0
coins = 0
// Load game state
let defaults = NSUserDefaults.standardUserDefaults()
highScore = defaults.integerForKey("highScore")
coins = defaults.integerForKey("coins")
}
func saveState() {
// Update highScore if the current score is greater
highScore = max(score, highScore)
// Store in user defaults
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highScore, forKey: "highScore")
defaults.setInteger(coins, forKey: "coins")
NSUserDefaults.standardUserDefaults().synchronize()
}
class var sharedInstance: GameState {
struct Singleton {
static let instance = GameState()
}
return Singleton.instance
}
}
And the GameScene.swift:
import SpriteKit
import CoreMotion
import GameplayKit
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let PlatformNormal: UInt32 = 0b10 // 2
static let PlatformBreakable: UInt32 = 0b100 // 4
static let CoinNormal: UInt32 = 0b1000 // 8
static let CoinSpecial: UInt32 = 0b10000 // 16
static let Edges: UInt32 = 0b100000 // 32
}
class GameScene: SKScene, SKPhysicsContactDelegate {
// Other Properties
...
var player: SKSpriteNode!
// HUD
var hudNode: SKNode!
var lblScore: SKLabelNode!
var lblCoins: SKLabelNode!
override func didMoveToView(view: SKView) {
....
// HUD
hudNode = SKNode()
hudNode.zPosition = 1000
cameraNode.addChild(hudNode)
// Coins
let coin = SKSpriteNode(imageNamed: "powerup05_1")
coin.position = convertPoint(CGPoint(x: 300, y: self.size.height-100), toNode: cameraNode)
coin.zPosition = 1000
hudNode.addChild(coin)
lblCoins = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblCoins.fontSize = 70
lblCoins.fontColor = SKColor.whiteColor()
lblCoins.position = convertPoint(CGPoint(x: 375, y: self.size.height-100), toNode: cameraNode)
lblCoins.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
lblCoins.zPosition = 1000
lblCoins.text = String(format: "X %d", GameState.sharedInstance.coins)
hudNode.addChild(lblCoins)
// Score
// 4
lblScore = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblScore.fontSize = 70
lblScore.fontColor = SKColor.whiteColor()
lblScore.position = convertPoint(CGPoint(x: self.size.width-325, y: self.size.height-100), toNode: cameraNode)
lblScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right
lblScore.zPosition = 1000
lblScore.text = "0"
hudNode.addChild(lblScore)
}
func setupNodes() {
...
player = fgNode.childNodeWithName("Player") as! SKSpriteNode
}
func createStarAtPosition(position: CGPoint, ofType type: CoinType) -> CoinNode {
// 1
let node = CoinNode()
let thePosition = CGPoint(x: position.x * scaleFactor, y: position.y)
node.position = thePosition
node.name = "NODE_COIN"
// 2
node.coinType = type
var sprite: SKSpriteNode
if type == .Special {
sprite = SKSpriteNode(imageNamed: "CoinSpecial")
} else {
sprite = SKSpriteNode(imageNamed: "Coin")
}
node.addChild(sprite)
// 3
node.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width / 2)
// 4
node.physicsBody?.dynamic = false
node.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Coin
node.physicsBody?.collisionBitMask = 0
node.physicsBody?.contactTestBitMask = 0
return node
}
func didBeginContact(contact: SKPhysicsContact) {
let other = contact.bodyA.categoryBitMask == PhysicsCategory.Player ? contact.bodyB : contact.bodyA
var updateHUD = false
let whichNode = (contact.bodyA.node != player) ? contact.bodyA.node : contact.bodyB.node
// Code crashes here
let another = whichNode as! GameObjectNode
updateHUD = another.collisionWithPlayer(player)
if updateHUD {
lblCoins.text = String(format: "X %d", GameState.sharedInstance.coins)
lblScore.text = String(format: "%d", GameState.sharedInstance.score)
}
switch other.categoryBitMask {
case PhysicsCategory.CoinNormal:
if let coin = other.node as? SKSpriteNode {
emitParticles("CollectNormal", sprite: coin)
jumpPlayer()
runAction(soundCoin)
}
case PhysicsCategory.CoinSpecial:
if let coin = other.node as? SKSpriteNode {
emitParticles("CollectSpecial", sprite: coin)
boostPlayer()
runAction(soundBoost)
}
case PhysicsCategory.PlatformNormal:
if let platform = other.node as? SKSpriteNode {
if player.physicsBody!.velocity.dy < 0 {
platformAction(platform, breakable: false)
jumpPlayer()
runAction(soundJump)
}
}
case PhysicsCategory.PlatformBreakable:
if let platform = other.node as? SKSpriteNode {
if player.physicsBody!.velocity.dy < 0 {
platformAction(platform, breakable: true)
jumpPlayer()
runAction(soundBrick)
}
}
default:
break;
}
}
I dont understand the code you use in didBeganContact, but you can define the contact bodies in this way:
enum Ctg:UInt32
{
case Coin = 1
case Hero = 2
case Villain = 4
case Car = 8
}
var hero = SKSpriteNode()
hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
hero.physicsBody?.categoryBitMask = Ctg.Hero.rawValue
hero.physicsBody?.contactTestBitMask = Ctg.Coin.rawValue | Ctg.Villian.rawValue
var coin = SKSpriteNode()
coin.physicsBody = SKPhysicsBody(rectangleOfSize: coin.size)
coin.physicsBody?.categoryBitMask = Ctg.Coin.rawValue
coin.physicsBody?.contactTestBitMask = Ctg.Hero.rawValue
func didBeginContact(contact: SKPhysicsContact)
{
var first = SKNode()
var sec = SKNode()
// this way you ensure that the first body is the most valuable Ctg (enum)
if contact.bodyA.node?.physicsBody?.categoryBitMask > contact.bodyB.node?.physicsBody?.categoryBitMask
{
first = contact.bodyA.node!
sec = contact.bodyB.node!
}
else
{
first = contact.bodyB.node!
sec = contact.bodyA.node!
}
// this part be sure that the category of first it is of most value that sec
if first.physicsBody!.categoryBitMask == Ctg.Hero.rawValue && sec.physicsBody!.categoryBitMask == Ctg.Coin.rawValue
{
hero.coins++
scene.labelCoins.text = String(coins)
}
if first.physicsBody!.categoryBitMask == Ctg.Villain.rawValue && sec.physicsBody!.categoryBitMask == Ctg.Hero.rawValue
{
gameOver = true
hero.removeFromParent()
lostGame()
}
}

How may i detect contact and collision correctly? Swift iOS SKScene

The problem is i can't detect the collision //or contact in any way i have found on the internet
This is my code:
The declaration of my masks:
private let ballCategory : UInt32 = 0x1 << 0
private let holeCategory : UInt32 = 0x1 << 1
The adding of both the hole and the ball:
func addHole(#size : CGSize) {
let actionMoveDown = SKAction.moveToY(CGRectGetMidY(self.frame)-500, duration: 4.7)
let hole = shapedHoles()
let UT = UTIL()
var position:CGFloat
let randomPosition = UT.randomNumberWith(Min: 1, Max: 3)
switch randomPosition{
case 1:
position = CGRectGetMidX(self.frame)
case 2:
position = CGRectGetMidX(self.frame)+size.width
default:
position = CGRectGetMidX(self.frame)-(size.width)
}
var createdHole = hole.createHoleAtPosition(position: CGPointMake(position ,CGRectGetMaxY(self.frame) + (size.height/2)),size: size )//CGSizeMake(CGRectGetMaxX(self.frame)/3 - 10, 70)
createdHole.physicsBody = SKPhysicsBody(rectangleOfSize: createdHole.frame.size)
createdHole.physicsBody?.categoryBitMask = holeCategory
createdHole.physicsBody?.collisionBitMask = 0
createdHole.physicsBody?.contactTestBitMask = ballCategory
createdHole.physicsBody?.affectedByGravity = false
createdHole.physicsBody?.dynamic = false
lastHolePosition = randomPosition
createdHole .runAction(actionMoveDown)
self.addChild(createdHole)
}
func addSphere(){
let mainCharacterController = circle()
let character: (SKNode) = mainCharacterController.createCircleAtPosition(position: CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame)+100))
character.physicsBody = SKPhysicsBody(circleOfRadius: character.frame.size.height/2)
character.physicsBody?.categoryBitMask = ballCategory
character.physicsBody?.collisionBitMask = 0
character.physicsBody?.contactTestBitMask = holeCategory
character.physicsBody?.affectedByGravity = false
character.physicsBody?.dynamic = false
self.addChild(character)
} func addHole(#size : CGSize) {
let actionMoveDown = SKAction.moveToY(CGRectGetMidY(self.frame)-500, duration: 4.7)
let hole = shapedHoles()
let UT = UTIL()
var position:CGFloat
let randomPosition = UT.randomNumberWith(Min: 1, Max: 3)
switch randomPosition{
case 1:
position = CGRectGetMidX(self.frame)
case 2:
position = CGRectGetMidX(self.frame)+size.width
default:
position = CGRectGetMidX(self.frame)-(size.width)
}
var createdHole = hole.createHoleAtPosition(position: CGPointMake(position ,CGRectGetMaxY(self.frame) + (size.height/2)),size: size )//CGSizeMake(CGRectGetMaxX(self.frame)/3 - 10, 70)
createdHole.physicsBody = SKPhysicsBody(rectangleOfSize: createdHole.frame.size)
createdHole.physicsBody?.categoryBitMask = holeCategory
createdHole.physicsBody?.collisionBitMask = 0
createdHole.physicsBody?.contactTestBitMask = ballCategory
createdHole.physicsBody?.affectedByGravity = false
createdHole.physicsBody?.dynamic = false
lastHolePosition = randomPosition
createdHole .runAction(actionMoveDown)
self.addChild(createdHole)
}
func addSphere(){
let mainCharacterController = circle()
let character: (SKNode) = mainCharacterController.createCircleAtPosition(position: CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame)+100))
character.physicsBody = SKPhysicsBody(circleOfRadius: character.frame.size.height/2)
character.physicsBody?.categoryBitMask = ballCategory
character.physicsBody?.collisionBitMask = 0
character.physicsBody?.contactTestBitMask = holeCategory
character.physicsBody?.affectedByGravity = false
character.physicsBody?.dynamic = false
self.addChild(character)
}
And last but not least the didBeginContactMethod
func didBeginContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody!
var secondBody: SKPhysicsBody!
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & holeCategory) != 0 &&
(secondBody.categoryBitMask & ballCategory) != 0 {
println("HO")
}
}
Thank you and hope you know what is happening, and if you need any extra code just comment it
You have to make sure that the SKScene subclass you are using also implements the SKPhysicsContactDelegate protocol. For example, it would look like this.
class MyScene : SKScene, SKPhysicsContactDelegate
Then you have to set your physics worlds contact delegate to yourself.
override init() {
self.physicsWorld.contactDelegate = self;
}
Tell me how this works out, but it should solve the problem and successfully allow you to listen in on collisions.
There is a couple things it might be. First you can try using an enum for the contact categories.
enum collisionBodies:UInt32 {
case ballCategory = 1
case holeCategory = 2
}
func Collisions() {
character.physicsBody.categoryBitMask = collisionBodies.ballCategory.rawValue
character.physicsBody.contactTestBitMask = collisionBodies.holeCategory.rawValue
character.physicsBody.collisionBitMask = 0
createdHole.physicsBody.categoryBitMask = collisionBodies.holeCategory.rawValue
createdHole.physicsBody.contactTestBitMask = collisionBodies.ballCategory.rawValue
createdHole.physicsBody.collisionBitMask = 0
}
Also try setting one of your physics bodies to dynamic = true or collisions will likely not work.
A better way to test for collisions in the didBeginContact function is to use a switch statement.
func didBeginContact(contact: SKPhysicsContact) {
let categoryMask = contact.BodyA.categoryBitMask | contact.BodyB.categoryBitMask
switch (categoryMask) {
case collisionBodies.holeCategory.rawValue | collisionBodies.ballCategory.rawValue:
//code to run when contact is detected
default:
return
}
}

Resources