Search code examples
iossprite-kitskphysicsjoint

SKPhysicsJointLimit EXC_BAD_ACCESS?


I'm using Sprite Kit (iOS), but whenever I try to add a SKPhysicsJointLimit to the physicsWorld, the app crashes with EXC_BAD_ACCESS (code=1, address=0xc0). Other joint types work fine, which is what's confusing me. Here's an example of what crashes:

var node1 = SKSpriteNode(color: SKColor.blueColor(), size: CGSize(width: 50, height: 50))
node1.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 50, height: 50))
self.addChild(node1)

var node2 = SKSpriteNode(color: SKColor.blueColor(), size: CGSize(width: 50, height: 50))
node2.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 50, height: 50))
self.addChild(node2)

var joint = SKPhysicsJointLimit()
joint.maxLength = 1000
joint.bodyA = node1.physicsBody
joint.bodyB = node2.physicsBody
self.physicsWorld.addJoint(joint)

When I replace SKPhysicsJointLimit() with SKPhysicsJointFixed() (and remove the line setting maxLength) or some other joint type, the code works as expected.

I'm new to Sprite Kit, any ideas on how to solve this?


Solution

  • The app is crashing because you're not setting the joint's anchor point properties. From the docs, anchorA is

    A connection point on the first body in the scene’s coordinate system.

    and anchorB is

    A connection point on the second body in the scene’s coordinate system.

    Here's an example of how to create a SKPhysicsJointLimit object with physics bodies and anchor points as arguments:

        let joint = SKPhysicsJointLimit.jointWithBodyA(node1.physicsBody!, bodyB: node2.physicsBody!, anchorA: node1.position, anchorB: node2.position)
        joint.maxLength = 1000
        physicsWorld.addJoint(joint)
    

    I'm not sure if you can't set the anchor points directly.