0
votes

I'm working on a game with a primary player as an SKSpriteNode. The game has a concept of powerups that can be acquired, and each player can have a set of attachments.

I have a protocol for attachments defined as:

@protocol ESPlayerAttachment <NSObject>

@required

-(ESPlayerAttachmentType)attachmentType;

@optional

-(void)willAttachToPlayer:(ESPlayerSpriteNode *)player;
-(void)didDetachFromPlayer:(ESPlayerSpriteNode *)player;
-(void)player:(ESPlayerSpriteNode *)player willUseAttachmentInParent:(SKNode *)parent;

@end

Additionally, I have a protocl for powerups defined as:

@protocol ESPlayerPowerup <NSObject>

-(void)acquiredByPlayer:(ESPlayerSpriteNode *)player;

@end

Finally, I have a physics body on the power up box, as well as one on the player so that I can detect the collision and attach the powerup. As an example, I have a shield powerup that is implemented as:

-(void)willAttachToPlayer:(ESPlayerSpriteNode *)player
{
    [player detachAttachmentsOfType:ESPlayerAttachmentTypeShield];
    __weak ESPlayerShipSpriteNode *weakPlayer = player;
    [player.parent addChild:_shield];
    _shield.position = CGPointMake(player.position.x, player.position.y + 0.1f * _shield.size.height);
    [self performSelector:@selector(detachFromPlayer:) withObject:weakPlayer afterDelay:15.0f];
}

What's bothering me is that if I attach the shield powerup to the player in my SKScene class (in the update or didMoveToView methods), everything works. The shield is positioned correctly. However, if I add it through the ESPlayerPowerup method (which gets called during a collision with the player), the node gets positioned relative to SKScene, so it ends up in the bottom left corner of the screen. I can't seem to figure out what the difference is (there's only one instance of ESPlayerSpriteNode in the game, so I'm relatively confident that isn't the problem)

1
[player.parent addChild:_shield] - You add the shield node to the player's parent node (SKScene node ?), is that on purpose ?giorashc
@giorashc Yeah, the player is an SKSpriteNode contained within a SKNode (the parent isn't SKScene). The reason for this is that I need the attachments (the shield in this case) to share a common parent with the player.Colin M
I don't see some of the code you mention, but I can only assume it's because you're dealing with different coordinate systems depending on what object is attempting to position the shield, and what object the shield is parented to.Cooper Buckingham

1 Answers

0
votes

For what it's worth, I ended up finding this post on SO, which has solved my problem:

SKSPriteNode position changes to 0,0 for no reason

It would seem to be a bug in SpriteKit, but positioning the item before attaching the physicsBody does work, and positions it correctly.