Search code examples
swiftsprite-kitskphysicsbodyskphysicsjoint

SpriteKit build rope function not working


Here is my code:

 var red: SKSpriteNode?
var redHolding = false
/////
// MARK: didMove
/////
override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self

    if let r = self.childNode(withName: "red") as? SKSpriteNode { red = r }
    createRope(red!, 10)

}//

func createRope(_ anchorSprite: SKSpriteNode, _ numOfLinks: Int) {
    var links: [SKSpriteNode] = []
    anchorSprite.position = CGPoint(x: 0, y: 0)

    for i in 0...numOfLinks {
        let link = SKSpriteNode(color: UIColor.black, size: CGSize(width: 20, height: 30))
        link.position = CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY - link.frame.height/2)
        link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)
        link.physicsBody?.isDynamic = true
        link.physicsBody?.allowsRotation = true
        link.physicsBody?.affectedByGravity = true
        link.physicsBody?.categoryBitMask = 4
        self.addChild(link)
        var joint = SKPhysicsJointPin()
        links.append(link)
        if i == 0 {
            joint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: link.physicsBody!, anchor: CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY))
        } else {
            link.position = CGPoint(x: anchorSprite.frame.midX, y: (links[i-1].frame.minY - links[i-1].frame.height/2) - link.frame.height/2)
            joint = SKPhysicsJointPin.joint(withBodyA: links[i-1].physicsBody!, bodyB: links[i].physicsBody!, anchor: CGPoint(x: links[i-1].frame.minX, y: links[i-1].frame.minY))
        }
        physicsWorld.add(joint)
    }
}

I'm trying to build a function that programmatically creates a rope and I could be way off so far, but I'm having an issue and I don't understand why.

I get an error "unexpectedly found nil while unwrapping optional"

It happens for the "Link" variable with its physics body when I try to make the Joint.

I don't understand why and I keep moving things around to try to fix it with no success.

Does anyone see what is wrong with the code?

Thanks for any help.


Solution

  • You need to remove the ? after the physicsBody property of the link.

    Old:

    link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)
    

    New:

    link.physicsBody = SKPhysicsBody(rectangleOf: link.size)