Casting custom SKSpriteNode class after collision

164 views Asked by At

I've got a couple of custom classes derived from SKSpriteNode and when they collide I want to call a method from the custom "Treat" class but it crashes on impact with the error.. " Unexpectedly found Nil when unwrapping an Optional value"

This is the Treat class...

import UIKit
import SpriteKit

class Treat: SKSpriteNode {

var isActive: Bool!

override init(texture: SKTexture!, color: SKColor, size: CGSize) {
    self.isActive = true

    super.init(texture: texture, color: color, size: size)

    self.texture = SKTexture(imageNamed: "treat1")
    self.zPosition = 3
    self.size = CGSize(width: 25, height: 25)
    self.physicsBody = SKPhysicsBody(rectangleOf: self.size)

    self.physicsBody?.friction = 0.1
    self.physicsBody?.restitution = 0.8
    self.physicsBody?.mass = 0.01
    self.physicsBody?.affectedByGravity = true
    self.physicsBody?.allowsRotation = true
    self.physicsBody?.isDynamic = true
    self.physicsBody?.categoryBitMask = PhysicsCategory.Treat
    self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
    self.physicsBody?.collisionBitMask = PhysicsCategory.Ground
    self.physicsBody?.usesPreciseCollisionDetection = true
    self.name = "Treat";

    let rotateDuration = Double(arc4random()) / 0xFFFFFFFF
    let rotateAction = SKAction.rotate(byAngle: CGFloat(M_PI), duration: rotateDuration)
    let rotateActionRepeatingForever = SKAction.repeatForever(rotateAction)
    self.run(rotateActionRepeatingForever)

}

convenience init(color: SKColor, isActive: Bool = false) {
    let size = CGSize(width:0, height: 0);
    self.init(texture:nil, color: color, size: size)
    self.isActive = isActive
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func throwTreat() {
    NSLog("Throwing Treat")
    let arc4randoMax:Double = 0x100000000
    let upper = 2.0
    let lower = 4.4
    let throwableAngle = Float32((Double(arc4random()) / arc4randoMax) * (upper - lower) + lower)

    self.physicsBody?.applyImpulse(CGVector(dx: CGFloat(-throwableAngle),dy: CGFloat(throwableAngle)))
}

func removeTreat(showEffect: Bool) {
    if self.isActive != false {
        self.isActive = false
        if showEffect != false {

        }
        self.removeFromParent()
    }

}

func onImpactWithPlayer() {
    self.removeFromParent()
}


}

And this is the physics collision detection..

 func didBegin(_ 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 & PhysicsCategory.Player != 0) &&
        (secondBody.categoryBitMask & PhysicsCategory.Ground != 0)) {
        self.playerNode.isJumping = false
    }


    if ((firstBody.categoryBitMask & PhysicsCategory.Player != 0) &&
        (secondBody.categoryBitMask & PhysicsCategory.Treat != 0)) {
        levelScore = levelScore + 1
        (secondBody.node as! Treat).onImpactWithPlayer() // This line crashes

    }

}

I'm new to swift and Object Oriented Programming so its not making a lot of sense at the moment. I know its a simple fix and I'm being stupid...

1

There are 1 answers

1
Luca Angeletti On BEST ANSWER

Your code seems mostly correct.

What I believe is happening here

When 2 physics bodies collide, the didBegin(_ contact: SKPhysicsContact) can be called several times over the same frame.

Since here

(secondBody.node as! Treat).onImpactWithPlayer()

you are removing Treat from the scene graph, the next time didBegin(_ contact:) is invoked over the same frame you get a crash because the node has been removed.

Solution

Just replace this

(secondBody.node as! Treat).onImpactWithPlayer()

with this

 (secondBody.node as? Treat)?.onImpactWithPlayer()