0

I'm trying to create a chain-like structure in SpriteKit and I'm having trouble understanding the behavior of SKPhysicsJointLimit's maxLength property. It seems not to do anything at all.

This question didn't solve my problem.

According to the documentation, maxLength is The maximum distance allowed between the two physics bodies connected by the limit joint.

However, my two nodes become oriented much farther apart than their maxLength value. It's true that I'm setting their initial positions to be farther apart than maxLength -- but I would expect the nodes to pull together during the simulation, as if tied together by a stretchy rope. Instead, the nodes remain far apart.

So, here's some code that sets a joint between two SKSpriteNodes.

let screen = UIScreen.main.bounds
let bodyA = SKSpriteNode(imageNamed: "box.png")
let bodyB = SKSpriteNode(imageNamed: "box.png")

bodyA.size = CGSize(width: 20, height: 20)
bodyB.size = CGSize(width: 20, height: 20)
        
bodyA.position = CGPoint(x: screen.width*0.4, y: screen.height*0.8)
bodyB.position = CGPoint(x: screen.width*0.6, y: screen.height*0.8)
        
bodyA.physicsBody = SKPhysicsBody(circleOfRadius: 20)
bodyB.physicsBody = SKPhysicsBody(circleOfRadius: 20)

addChild(bodyA)
addChild(bodyB)

let pinJoint = SKPhysicsJointLimit.joint(withBodyA: bodyA.physicsBody!, bodyB: bodyB.physicsBody!, anchorA: CGPoint(x: 0.5, y: 0.5), anchorB: CGPoint(x: 0.5, y: 0.5))

//This doesn't seem to do anything:
pinJoint.maxLength = 5.0

scene?.physicsWorld.add(pinJoint)

In the simulation, it's clear that there is a physics joint connecting the two nodes -- it's just that the nodes are much farther apart than they should be.

Why doesn't my maxLength value change the behavior of my two nodes, and how do I fix the problem? What am I not understanding?

Thanks for your input!

West1
  • 1,430
  • 16
  • 27
  • I haven't tried physics joints and do not have access to my Mac now, but the documentation says that the anchor points must be in scene coordinates. So your (0.5, 0.5) for both bodies doesn't seem correct. – bg2b Dec 27 '20 at 16:41
  • @bg2b Thanks for your help! I'll experiment with some different anchor points and see what happens. – West1 Dec 27 '20 at 16:54
  • @bg2b Changing the anchor points to scene coordinates like I should have been doing from the beginning seems to have solved the problem entirely. If you write it up as an answer, I'll accept it. Thanks. – West1 Dec 27 '20 at 17:04

1 Answers1

0

Be sure that the anchor points are in scene coordinates, as described in the documentation. The (0.5, 0.5) is likely intended to be "center of the sprite" or something like that, but that's not correct for a joint.

bg2b
  • 1,939
  • 2
  • 11
  • 18