1

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

4

1 回答 1

1

代替手动矩形,使用精灵的边界框。

         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];
}
于 2013-01-24T04:21:21.950 回答