0

我有一个带有方向键和 2 个按钮的游戏手柄。它们都是数字的(不是模拟的)。

我有一个处理他们事件的程序:

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

我通过命令调用它:

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

[ship shoot] 从 Weapon 类调用射击函数:

-(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];
}

问题是武器射出太多子弹。是否可以在不使用每个按钮和方向键分开的计时器和功能的情况下减少它们的数量?

4

2 回答 2

1

使用 Delta 来跟踪拍摄之间的时间,并且仅在 delta 增加了一定数量时才进行拍摄。这是一种常见的处理方式,您不需要每一帧。

您需要保留一个 iVar 已用时间计数器,在每次拍摄时将其递增 Delta,然后测试已用时间量以查看它是否满足您所需的间隔阈值;如果是,则拍摄并将经过的时间重置为 0。

于 2012-04-01T05:38:22.607 回答
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 游戏开发”一书中的原始代码。但我可以稍微改进一下这段代码。

更新

我的代码比原始代码更难理解,但它具有正确的结构。它的含义如下: - 全局定时器属于一个场景;- 船可以通过武器射击;- 武器可以用子弹射击并且子弹之间的延迟属于这种武器(不是原始示例中的场景)

Scene 类包含 totalTime 变量、ship 对象和以下处理计时器更新的方法:

-(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];
    }
}

Ship 类包含一个武器对象和一个射击方法(此方法不适用于此问题)。

Weapon 类包含 nextShotTime 变量和以下方法:

-(void)updateNextShotTime:(ccTime)currentTime
{
    nextShotTime = currentTime + 0.05f;
}
于 2012-04-13T08:21:35.750 回答