How to transfer a CCSprite from one parent to another?

社会主义新天地 提交于 2019-12-12 11:18:27

问题


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.


回答1:


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];


来源:https://stackoverflow.com/questions/6720615/how-to-transfer-a-ccsprite-from-one-parent-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!