Cannot change SKPhysicsJointLimit maxLength after adding a connection to SKPhysicsWorld in Sprite Kit

So, I created an SKSpriteNodes ring, which are essentially rectangles that are connected together using pin joints. I would like to pause this ring inside the SKShapeNode circle. I connected each of the nodes to SKShapeNode using SKPhysicsJointLimit.

All this works great, and I get the effect I'm looking for if I set maxLength to the “correct” number, which I determine subjectively.

I kept all the limitations of the joints inside the array, so I can get easy access, and I added them to the physical world.

It all works correctly and as expected, although it took a bit of work to get the correct code. These things are picky!

Now, what I really would like to do is set maxLength to some large number, and then gradually decrease this number over time, so that the ring goes from “freezing” to “stretched”

I tried various approaches - none of them seem to work. First, I tried:

SKAction *tighten = [SKAction customActionWithDuration:1 actionBlock:^(SKNode *node, CGFloat elapsedTime) {
    CGFloat t = elapsedTime/duration;
    CGFloat p = t*t;
    CGFloat newLimit = fromLimit*(1-p) + toLimit*p;
    for (int i = 0; i < _connectors.count; i++){
        [[_connectors objectAtIndex:i] setMaxLength:newLimit];
    }
}];

[_ring runAction:tighten];

but it just didn't do anything.

Finally, I realized that you seem to be unable to change the properties of a joint after it has been added to the physical world. So, I tried something like this in the scene update method:

        [scene.physicsWorld removeJoint:[_connectors objectAtIndex:i]];
        [[_connectors objectAtIndex:i] setMaxLength:newLimit];
        [scene.physicsWorld addJoint:[_connectors objectAtIndex:i]];

but that didn't work either. He threw an error:

'Cant add joint <PKPhysicsJointRope: 0x114e84350>, already exists in a world'

although I clearly deleted it. So I really don’t know where to go from here. The joint documentation and existing material on the Internet is very thin. I assume that the next thing I will try is to remove all the joints and add them, but it will be a huge pain.

!

+4
1

OP, , , . .

for joint in joints
{
    physicsWorld.removeJoint(joint)
    joint.maxLength = yourNewValue
    physicsWorld.addJoint(joint)
}
+1

Source: https://habr.com/ru/post/1532220/


All Articles