2013-01-24 34 views
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軸位置的一個)也不起作用。我該如何解決這個問題?任何幫助和建議不勝感激

回答

1

而不是手動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]; 
} 
+0

非常感謝您的幫助。我只是將dest_y的值調整爲s.height + s.contentSize.height/2;現在它可以工作。這是我的遊戲唯一的問題。差不多,我仍然有這種停頓的情景。非常感謝! – user1597438

+0

我還有一個問題。我如何推遲精靈的下降?就像大概20秒鐘一樣,一次只能有一個精靈落下,然後更多的精靈開始下落。我怎樣才能做到這一點? – user1597438

+0

不知道你是如何產生丟棄精靈,如果它是在單獨的schedular,那麼你可以通過unScheduling和重新調度再次更改schedular持續時間......更好地發佈在代碼片段的單獨問題...謝謝 – Guru

相關問題