SpriteKit:如何创建基本物理关节

时间:2013-10-13 09:00:12

标签: objective-c ios7 physics sprite-kit skphysicsbody

我正在尝试在两个SKPhysicsBodies之间创建简单的关节。但是,他们表现得非常奇怪。 我很清楚锚点应该在场景坐标上。请查看附带的源代码。

例如,这是在矩形上附加小方块后固定关节的结果。

-(void)createFixedJointOnScene:(SKScene*)scene

{

//Adding Rectangle

    SKSpriteNode* backBone = [[SKSpriteNode alloc] initWithColor:[UIColor whiteColor] size:CGSizeMake(20, 200)];
backBone.position = CGPointMake(CGRectGetWidth(self.frame)/2.0, CGRectGetHeight(self.frame)/2.0);
backBone.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:backBone.size];
backBone.physicsBody.categoryBitMask = GFPhysicsCategoryRectangle;
backBone.physicsBody.collisionBitMask = GFPhysicsCategoryWorld;
[scene addChild:backBone];

//Adding Square
SKSpriteNode* head = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(40, 40)];
head.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:head.size];
head.position = CGPointMake(backBone.position.x, backBone.position.y-40);
head.physicsBody.categoryBitMask = GFPhysicsCategorySquare;
head.physicsBody.collisionBitMask = GFPhysicsCategoryWorld;
[scene addChild:head];

//Pinning Rectangle and Square
NSLog(@"Head position %@", NSStringFromCGPoint(head.position));
SKPhysicsJointFixed* pin =[SKPhysicsJointFixed jointWithBodyA:backBone.physicsBody bodyB:head.physicsBody anchor:head.position];
[self.physicsWorld addJoint:pin];

}

enter image description here

https://dl.dropboxusercontent.com/u/62559842/PhysicsTest.zip

谢谢。

1 个答案:

答案 0 :(得分:13)

谢谢Smick ..在将Smick的代码与我的比较后,我发现这两行的顺序导致了这个问题。

head.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:head.size];
head.position = CGPointMake(backBone.position.x, backBone.position.y-40);

当我在设置物理体之前设置Sprite的位置时,一切都开始正常工作。

head.position = CGPointMake(backBone.position.x, backBone.position.y-40);
head.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:head.size];

现在我已将Smick的代码附加到完整代码并在此处附加链接。享受。

https://dl.dropboxusercontent.com/u/62559842/PhysicsTest_Final_Working.zip