如何在精灵到达某一点或被触摸时删除它?

时间:2013-01-24 02:25:13

标签: objective-c cocos2d-iphone

我正在尝试在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轴位置的语句)也不起作用。我该如何解决这个问题?非常感谢任何帮助和建议

1 个答案:

答案 0 :(得分:1)

使用sprite的边界框而不是手动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];
}