当前位置: 动力学知识库 > 问答 > 编程问答 >

cocos2d iphone - How to transfer a CCSprite from one parent to another?

问题描述:

I have a CCSprite called sprite that is a child of a CCLayer called movingLayer that is itself a child of the current CCLayer running my game logic, so it is self in this case. movingLayer is moving back and forth across the screen in a repeat forever action and sprite is riding along on it. I want to get sprite to "get off" of movingLayer and "get on" to self where it can do some actions of its own.

When I try to do this, I need to tell movingLayer to remove sprite and self to add sprite. This is what I did...

- (void)attack:(id)sender

{

[sprite stopAllActions];

[movingLayer removeChild:sprite cleanup:YES];

[self addChild:sprite z:1];

CGFloat distance = ccpDistance(sprite.position, ccp(sprite.position.x, -sprite.contentSize.height/2));

id goDown = [CCMoveTo actionWithDuration:distance/moveDuration position:ccp(sprite.position.x, -sprite.contentSize.height/2)];

id repeatDown = [CCRepeatForever actionWithAction:[CCSequence actions:[CCMoveTo actionWithDuration:0 position:ccp(sprite.position.x, sprite.contentSize.height/2+self.contentSize.height)], [CCMoveTo actionWithDuration:moveDuration position:ccp(sprite.position.x, -sprite.contentSize.height/2)], nil]];

id attackAction = [CCSequence actions:goDown, repeatDown, nil];

[sprite runAction:attackAction];

}

I think stopAllActions is redundant, but that's not the problem. If I remove sprite from movingLayer before adding it to self I crash for accessing a zombie, and if I try to add it to self first, I crash for trying to add something already added.

网友答案:

Have you tried setting cleanup to NO?

Alternatively, try to retain sprite before you remove it from movingLayer, then release it when you're done with it:

[sprite retain];
[movingLayer removeChild:sprite cleanup:YES];
[self addChild:sprite z:1];
[sprite release];
分享给朋友:
您可能感兴趣的文章:
随机阅读: