如何删除一个精灵,当它达到某个点或它被触摸?
问题描述:
我想在cocos2d中制作游戏,其中我从屏幕顶部滴下精灵。现在,一旦这个精灵被挖掘出来,它就会回升。这对我来说工作得很好,但是,有些情况下,精灵在离开屏幕后会回落。此外,我的精灵一旦到达屏幕上的某个y轴位置,它们就不会消失。这里是我的代码部分如何删除一个精灵,当它达到某个点或它被触摸?
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint loc = [[CCDirector sharedDirector]convertToGL:[touch locationInView:[touch view]]];
CGRect rect = CGRectMake(sprite.position.x - (sprite.contentSize.width/2), sprite.position.y - (sprite.contentSize.height/2), sprite.contentSize.width, sprite.contentSize.height);
if(CGRectContainsPoint(rect, loc))
{
[sprite runAction:[CCCallFuncN actionWithTarget:self selector:@selector(spriteCaught)]];
}}
-(void)spriteCaught
{
//currentPos is an integer to get the current position of the sprite
id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(currentPos, 500)];
[sprite runAction:[CCSequence actions:moveUp, nil]];
if(sprite.position.y >= 480)
{
[self removeChild:sprite cleanup:YES];
}}
而且,我不知道如果我的语法是正确的,但我的条件语句(即检查在精灵的y轴位置的一个)也不起作用。我该如何解决这个问题?任何帮助和建议不胜感激
答
而不是手动rect,使用精灵的边界框。
if(CGRectContainsPoint([sprite boundingBox], loc))
还更新spriteCaught函数。
-(void)spriteCaught
{
CGSize s = [[CCDirector sharedDirector] winSize];
float dest_y = s.height+sprite.contentSize.height*0.5f; //assumed ur sprite's anchor y = 0.5
//currentPos is an integer to get the current position of the sprite
id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(sprite.position, dest_y)];
id calBlokc = [CCCallBlockN actionWithBlock:^(CCNode *node)
{
//here node = sprite tht runs this action
[node removeFromParentAndCleanup:YES];
}];
id sequence = [CCSequence actions:moveUp, calBlokc, nil];
[sprite runAction:sequence];
}
非常感谢您的帮助。我只是将dest_y的值调整为s.height + s.contentSize.height/2;现在它可以工作。这是我的游戏唯一的问题。差不多,我仍然有这种停顿的情景。非常感谢! – user1597438
我还有一个问题。我如何推迟精灵的下降?就像大概20秒钟一样,一次只能有一个精灵落下,然后更多的精灵开始下落。我怎样才能做到这一点? – user1597438
不知道你是如何产生丢弃精灵,如果它是在单独的schedular,那么你可以通过unScheduling和重新调度再次更改schedular持续时间......更好地发布在代码片段的单独问题...谢谢 – Guru