Search code examples
swiftsprite-kitskphysicsjoint

Swift SpriteKit SKPhysicsJointPin


I'm trying to implement a rope in Swift SpriteKit and to add physics to it, the position is good for all, but they won't attach, when I hit play they all fall except the first one which is the "holder". Here is my code:

    // create rope holder
    let chainHolder = SKSpriteNode(imageNamed: "chainHolder")

    chainHolder.position.y = self.frame.maxY - chainHolder.size.height

    chainHolder.physicsBody = SKPhysicsBody(circleOfRadius: chainHolder.size.width / 2)
    chainHolder.physicsBody?.dynamic = false
    //chainHolder.physicsBody?.allowsRotation = true

    chains.append(chainHolder)
    addChild(chainHolder)

    // add each of the rope parts
    for i in 0...5 {

        let chainRing = SKSpriteNode(imageNamed: "chainRing")
        let offset = chainRing.size.height * CGFloat(i + 1)
        chainRing.position = CGPointMake(chainHolder.position.x, chainHolder.position.y - offset)
        chainRing.name = String(i)

        chainRing.physicsBody = SKPhysicsBody(rectangleOfSize: chainRing.size)
        //chainRing.physicsBody?.allowsRotation = true

        chains.append(chainRing)
        addChild(chainRing)
    }

    // set up joints between rope parts
    for i in 1...5 {

        var nodeA = chains[i - 1]
        var nodeB = chains[i]
        var joint = SKPhysicsJointPin.jointWithBodyA(nodeA.physicsBody, bodyB: nodeB.physicsBody,
            anchor: CGPointMake(CGRectGetMidX(nodeA.frame), CGRectGetMinY(nodeA.frame)))

        physicsWorld.addJoint(joint)
    }

Solution

  • I found out that the problem was because I was setting the anchor point for the scene in (0.5, 0.5). If I leave it in (0, 0) everything is ok.