Search code examples
iosobjective-csprite-kitskphysicsbodyskphysicsjoint

Can I set anchor point of SKPhysicsJoint outside node?


Let's say I have two circles respectively at (0,0) and (0,1).

I have a SKPhysicsJoint between them and it is working good, now I want to separate them with a distance of 2 on runtime, meaning while physics are working in-game. How can I achieve this?

I've tried setting anchor points to (0,0) and (0,2) but something is bugged, although I see the joint it doesn't have any affect.

I want the circles smoothly push each other, as if the length of the spring has increased.

Everything works if I make a circle 'teleport' to a distance of 2 and then anchor the spring to it, but making a physics object teleport cause other bugs as you can guess.


Solution

  • Before adding the joint I 'teleported' the second object to the desired position, then added the joint and then 'teleported' back to the original position.

    Here is the code piece:

    SKSpriteNode* node1 = [_bodies objectAtIndex:loop];
         SKSpriteNode* node2 = [_bodies objectAtIndex:loop-1];
         CGPoint prev1 = node1.position;
         CGPoint prev2 = node2.position;
         node1.position = [((NSValue*)[positions objectAtIndex:loop]) CGPointValue];
         node2.position = [((NSValue*)[positions objectAtIndex:loop-1]) CGPointValue];
         [self AttachPoint:node1  secondPoint:node2 pos1:node1.position pos2:node2.posiiton] ;
         node1.position = prev1;
         node2.position = prev2;
    

    it is working as it is, but I'm not sure how efficient this is. I wish SKPhysicsJointSpring had a 'length' parameter that can be changed over time.