我正在用Sprite Kit测试针脚接头,我发现异常发生.
我想要的设置是:一个宽,平的盒子和两个圆圈;圆圈通过SKPhysicsPinJoints连接到盒子,因此它们可以作为轮子.
这是我的代码我试图使其尽可能简洁:
- (SKNode*) createWheelWithRadius:(float)wheelRadius { CGRect wheelRect = CGRectMake(-wheelRadius,-wheelRadius,wheelRadius*2,wheelRadius*2); SKShapeNode* wheelNode = [[SKShapeNode alloc] init]; wheelNode.path = [UIBezierPath bezierPathWithOvalInRect:wheelRect].CGPath; wheelNode.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:wheelRadius]; return wheelNode; } - (void) createCar { // Create the car SKSpriteNode* carNode = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(150,50)]; carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size]; carNode.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame)); [self addChild:carNode]; // Create the left wheel SKNode* leftWheelNode = [self createWheelWithRadius:30]; leftWheelNode.position = CGPointMake(carNode.position.x-80,carNode.position.y); [self addChild:leftWheelNode]; // Create the right wheel SKNode* rightWheelNode = [self createWheelWithRadius:30]; rightWheelNode.position = CGPointMake(carNode.position.x+80,carNode.position.y); [self addChild:rightWheelNode]; // Attach the wheels to the body CGPoint leftWheelPosition = leftWheelNode.position; CGPoint rightWheelPosition = rightWheelNode.position; SKPhysicsJointPin* leftPinJoint = [SKPhysicsJointPin jointWithBodyA:carNode.physicsBody bodyB:leftWheelNode.physicsBody anchor:leftWheelPosition]; SKPhysicsJointPin* rightPinJoint = [SKPhysicsJointPin jointWithBodyA:carNode.physicsBody bodyB:rightWheelNode.physicsBody anchor:rightWheelPosition]; [self.physicsWorld addJoint:leftPinJoint]; [self.physicsWorld addJoint:rightPinJoint]; }
我期望的是针接头锚定在他们的中心点;然而,当我测试这个,关节的锚点似乎是远离的.
我错过了一些很明显的东西吗?
解决方法
我也有这个问题,原因是在设置精灵位置之前设置物理体.
carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size]; carNode.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
将上述更改为
carNode.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame)); carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];
应该工作谢谢Smick