2012-03-31 73 views
0

我有一個方向鍵和2個按鈕的遊戲手柄。所有這些都是數字(不是模擬)。Cocos2d。降低火災(子彈)的速度(速度)?

我處理自己的事件過程:

-(void)gamepadTick:(float)delta 
{ 
    ... 
    if ([gamepad.B active]) { 
     [ship shoot]; 
    } 
    ... 
} 

而且我通過一個命令調用它:

[self schedule:@selector(gamepadTick:) interval:1.0/60]; 

[船拍]調用從武器級拍攝功能:

-(void)shoot 
{ 
    Bullet *bullet = [Bullet bulletWithTexture:bulletTexture]; 
    Ship *ship = [Ship sharedShip]; 
    bullet.position = [ship getWeaponPosition]; 
    [[[CCDirector sharedDirector] runningScene] addChild:bullet]; 

    CGSize winSize = [[CCDirector sharedDirector] winSize]; 
    int realX = ship.position.x; 
    int realY = winSize.height + bullet.contentSize.height/2; 
    CGPoint realDest = ccp(realX, realY); 

    int offRealX = realX - bullet.position.x; 
    int offRealY = realY - bullet.position.y; 
    float length = sqrtf((offRealX*offRealX) + (offRealY*offRealY)); 
    float velocity = 480/1; // 480pixels/1sec 
    float realMoveDuration = length/velocity; 

    [bullet runAction:[CCSequence actions:[CCMoveTo actionWithDuration:realMoveDuration position:realDest], 
         [CCCallFuncN actionWithTarget:self selector:@selector(bulletMoveFinished:)], nil]]; 
} 

-(void)bulletMoveFinished:(id)sender 
{ 
    CCSprite *sprite = (CCSprite *)sender; 
    [[[CCDirector sharedDirector] runningScene] removeChild:sprite cleanup:YES]; 
} 

問題是武器射出太多的子彈。是否可以減少它們的數量,而無需使用每個按鈕和方向鍵分開的定時器和功能?

回答

0
-(void) update:(ccTime)delta { 
totalTime += delta; 
if (fireButton.active && totalTime > nextShotTime) { 
    nextShotTime = totalTime + 0.5f; 
    GameScene* game = [GameScene sharedGameScene]; 
    [game shootBulletFromShip:[game defaultShip]]; 
} 
// Allow faster shooting by quickly tapping the fire button if (fireButton.active == NO) 
{ 
    nextShotTime = 0; 
} 
} 

這是Steffen Itterheim的「學習cocos2d遊戲開發」一書的原始代碼。 但我可以稍微改進一下這段代碼。

更新

這是很難理解我的代碼比原來的一個,但它有一個正確的結構。它意味着以下內容: - 全局計時器屬於一個場景; - 船隻可以通過武器射擊; - 武器可以與子彈和子彈之間的延遲拍攝屬於這種武器(不是場景如在最初的例子)

場景類包含TOTALTIME變量,船舶對象和下面的方法來處理定時器的更新:

-(void)update:(ccTime)delta 
{ 
    totalTime += delta; 

    if (!fireButton.active) { 
     ship.weapon.nextShotTime = 0; 
    } else if (totalTime > ship.weapon.nextShotTime) { 
     [ship.weapon updateNextShotTime:totalTime]; 
     [ship shoot]; 
    } 
} 

船級包含武器物體和射擊方法(該方法對於這個問題不是實際的)。

武器類包含nextShotTime變量和下面的方法:

-(void)updateNextShotTime:(ccTime)currentTime 
{ 
    nextShotTime = currentTime + 0.05f; 
} 
1

使用Delta記錄拍攝之間的時間,並且只有在delta增加一定量時才拍攝。這是一種常見的做事方式,你不需要每一幀。

您將需要保持一個iVar計數器的時間流逝,在每次拍攝時增加Delta值,然後測試流逝的時間量以查看它是否滿足您所需的間隔閾值;如果是的話,然後拍攝並將時間重置爲0.

+0

+1,但我發現同樣的事情的具體例子。如果沒有人想嘗試,那麼我會發布它 – Gargo 2012-04-03 22:00:21