2012-03-31 104 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