Sprite Kit pin joints appear to have an incorrect anchor

后端 未结 2 1784
南方客
南方客 2020-12-03 08:38

I\'m testing out pin joints with Sprite Kit, and I\'m finding something unusual happening.

My desired setup is this: one wide, flat box, and two circles; the circles

相关标签:
2条回答
  • 2020-12-03 09:19

    Try this code, I used yours and got weird issues, so started from scratch.

    - (SKShapeNode*) makeWheel
    {
        SKShapeNode *wheel = [[SKShapeNode alloc] init];
        CGMutablePathRef myPath = CGPathCreateMutable();
        CGPathAddArc(myPath, NULL, 0,0, 16, 0, M_PI*2, YES);
        wheel.path = myPath;
        return wheel;
    }
    
    
    - (void) createCar 
    {
    
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    
        // 1. car body
        SKSpriteNode *carBody = [SKSpriteNode spriteNodeWithColor:[UIColor whiteColor] size:CGSizeMake(120, 8)];
        carBody.position = CGPointMake(200, 200);
        carBody.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carBody.size];
        [self addChild:carBody];
    
        // 2. wheels
        SKShapeNode *leftWheel = [self makeWheel];
        leftWheel.position = CGPointMake(carBody.position.x - carBody.size.width / 2, carBody.position.y);
        leftWheel.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:16];
        [self addChild:leftWheel];
    
        SKShapeNode *rightWheel = [self makeWheel];
        rightWheel.position = CGPointMake(carBody.position.x + carBody.size.width / 2, carBody.position.y);
        rightWheel.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:16];
        [self addChild:rightWheel];
    
        // 3. Join wheels to car
        [self.physicsWorld addJoint:[SKPhysicsJointPin jointWithBodyA:carBody.physicsBody bodyB:leftWheel.physicsBody anchor:leftWheel.position]];
        [self.physicsWorld addJoint:[SKPhysicsJointPin jointWithBodyA:carBody.physicsBody bodyB:rightWheel.physicsBody anchor:rightWheel.position]];
    
        // 4. drive car
        [carBody.physicsBody applyForce:CGVectorMake(10, 0)];
    }
    
    0 讨论(0)
  • 2020-12-03 09:25

    I also had this issue and the cause is setting the physics body before setting the sprites position.

    carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];
    carNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    

    Change the above to

    carNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];
    

    It should work. Thanks Smick.

    SpriteKit: How to create Basic Physics Joints

    0 讨论(0)
提交回复
热议问题