0
我是cocos2d中的新成員。我們在創建新的精靈對象時遇到問題。它不會被移除到顯示器上。當我們添加新的生命時,Sprite對象不會被刪除(添加心靈精靈)。如何在cocos2d中創建觸摸時刪除精靈對象?
//這裏我創建了一個心形的生活。
-(id) init {
if((self=[super init])) {
hearthArray = [[NSMutableArray alloc] init];
lives = 4;
for(NSInteger ilive = 0; ilive<lives; ilive++){
CCSprite *hearth = [CCSprite spriteWithFile:@"hearth.png"];
hearth.position = ccp(((ilive+1)*50), winSize.height - 50);
[hearthArray insertObject:hearth atIndex:ilive];
[self addChild:hearth];
}
return self;
}
//下面的代碼去掉心臟(減少生命)。
- (void) addMonster:(ccTime)dt {
//select a random monster from the _monsters Array
int selectedMonster = arc4random() % [_monsters count];
Monster *monster = [_monsters objectAtIndex:selectedMonster];
int m = [monster movement];
CCSprite *spriteMonster = [[CCSprite alloc] initWithFile:[monster monsterSprite]];
spriteMonster.tag = [monster tag];
CGSize winSize = [CCDirector sharedDirector].winSize;
int minX = spriteMonster.contentSize.width/2;
int maxX = winSize.width - spriteMonster.contentSize.width/2;
int rangeX = maxX - minX;
int actualY = (arc4random() % rangeX) + minX;
//BLOCK 2 - Determine speed of the monster
int minDuration = [monster minVelocity];
int maxDuration = [monster maxVelocity];
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
if(m == 1){
spriteMonster.position = ccp(actualY,winSize.height + spriteMonster.contentSize.height/2);
[self addChild:spriteMonster];
//BLOCK 4 - Create the actions
CCMoveTo * actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(actualY,-spriteMonster.contentSize.height/2)];
CCCallBlockN * actionMoveDone = [CCCallBlockN actionWithBlock:^(CCNode *node) {
[_monstersOnScreen removeObject:node];
[node removeFromParentAndCleanup:YES];
// Remove lifes
lives--;
// [[hearthArray lastObject] removeFromParentAndCleanup:YES];
[self removeChild:[hearthArray lastObject] cleanup:YES];
[hearthArray removeLastObject];
NSLog(@"m=1 when array : %@",hearthArray);
if(lives == 0)
[[CCDirector sharedDirector] replaceScene:[HelloWorldLayer scene]];
}];
[spriteMonster runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
[_monstersOnScreen addObject:spriteMonster];
}
}
//在下面添加新生命使用for loop.when觸摸特定對象。
-(void)increaseLivesWhentouchCoin{
NSLog(@"lives is get when add live : %i",lives);
NSLog(@"hearthArray when toch coin: %@",hearthArray);
lives = lives+1;
NSLog(@"lives+1 : %i",lives);
for(NSInteger i = 0; i<lives; i++){
hearth = [CCSprite spriteWithFile:@"hearth.png"];
CGSize winSize = [CCDirector sharedDirector].winSize;
hearth.position = ccp(((i+1)*50), winSize.height-50);
[hearthArray insertObject:hearth atIndex:i];
[self addChild:hearth];
}
NSLog(@"hearthArray out for loop: %@",hearthArray);
}
請幫助我。預先感謝。
+1 @vivek Bansal謝謝。 – Rain