user3574603
user3574603

Reputation: 3628

SpriteKit/Objective-C: Applying SKPhysicsBody to parent node so it treats child nodes as one

I have an SKNode that is has two child SKShapeNodes.

+(instancetype)skeetWithRandomColorsAtPosition:(CGPoint)position WithSize:(CGFloat)size {

InnerSkeetNode *inner = [InnerSkeetNode innerSkeetWithHue:PurpleHue AtPosition:position WithSize:size];
OuterSkeetNode *outer = [OuterSkeetNode outerSkeetWithHue:BlueHue AtPosition:position WithSize:size];

SkeetNode *skeetnode = [SkeetNode node];
[skeetnode addChild:outer];
[skeetnode addChild:inner];

[skeetnode setUpPhysicsBody];

return skeetnode;
}

...so basically the parent node is made up of two shapes -- inner and outer -- of different colours.

Now I want to apply a physics body to skeetnode:

-(void)setUpPhysicsBody {
self.physicsBody = [SKPhysicsBody    
bodyWithRectangleOfSize:self.frame.size];
self.physicsBody.affectedByGravity = YES;
}

…but the problem is that it remains unaffected by the game's physics world.

However, the two child nodes will be affected if I set up physics bodies on them separately. The problem is, they act as two bodies. For collision purposes, I want to treat them as a single node -- hence adding them to the parent.

There's SKPhysicsJointFixed. But, after trying it out (and according to the documentation) I can only add the joint to a scene, not to a discrete node.

Is it possible to add to children to an SKNode and treat them as one physics body? Any help would be appreciated!

Upvotes: 1

Views: 129

Answers (1)

user3574603
user3574603

Reputation: 3628

Thanks, sangony. I double checked and found skeetnode.physicsBody was nil.

So I inherited SKSkeetNode from SKSpriteNode and created an instance this way:

SkeetNode *skeetnode = [SkeetNode spriteNodeWithTexture:nil size:CGSizeMake(size, size)];

Now it works perfectly.

Upvotes: 1

Related Questions