iPhone射击游戏子弹物理!

时间:2010-04-24 07:03:24

标签: iphone physics

在这里以“Galaga”的方式制作一款新的射击游戏(我最喜欢的射击游戏成长)。

以下是我对子弹物理学的代码:

-(IBAction)shootBullet:(id)sender{
imgBullet.hidden = NO;
timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(fireBullet) userInfo:Nil repeats:YES];
}

-(void)fireBullet{
imgBullet.center = CGPointMake(imgBullet.center.x + bulletVelocity.x , imgBullet.center.y + bulletVelocity.y);
if(imgBullet.center.y <= 0){
 imgBullet.hidden = YES;
 imgBullet.center = self.view.center;
 [timer invalidate];
}
}

无论如何,显而易见的问题是,一旦子弹离开屏幕,其中心就会被重置,所以每次按下“开火”按钮时我都会重复使用相同的子弹。

理想情况下,我希望用户能够在不导致程序崩溃的情况下发送“触发”按钮。我如何修改现有的代码,以便每次按下按钮时弹出一个子弹对象,然后在它退出屏幕后消失,或者与敌人发生碰撞?

感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:3)

你当然不希望定时器射击每个子弹,小行星,爆炸动画等,这将是可怕的。

大多数游戏都基于所谓的有限状态机。这本质上是一种跟踪游戏状态(即PLAYING,END_GAME,WAITING_FOR_OTHERPLAYERS)并基于此做出决定的方法。这种方法会通过一个计时器反复调用,就像你为子弹做的一样。我建议你这样设置你的游戏。现在关于那些子弹,当玩家点击开火按钮时,将另一个子弹添加到一系列事物中 - 这需要随着时间的推移自行调整。然后每次通过游戏循环,当状态指示时,迭代它们并告诉它们“updateYourself”。这也是您进行碰撞检测并启动爆炸动画,移除屏幕外物体等的地方。

希望有所帮助,

肯尼

更新:一些伪代码(即不会编译)应该更好地解释事情。请注意,我总是喜欢传递游戏时间,以便对象不知道实际时间,这是一个很好的做法,因为它不仅可以恢复游戏会话,非常适合调试,有时可以创建一个简洁的功能,它还意味着所有对象都获得相同的时间,而不是第一个对象的毫秒时间,这取决于它在数组中的位置。热点提示!哇哇!!

// implementation in MainGame class

  // After application has had its lunch....
- (void) applicationDidFinishLunching {
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:GAMETIME_INTERVAL target:self selector:@selector(myGameLoop)    userInfo:nil repeats:TRUE];
}

- (void) startGame {
    gameState = PLAYING;
// And most likely a whole bunch of other stuff
}

NSMutableArray * mTransientObjects;

- (void) fireButtonPressed:(float) atY andTime:(NSTimeInterval) fireTime {
    // I will assume only a "Y" variable for this game, Galaga style.
    Bullet * aBullet = [[Bullet alloc] initWithY:atY atTime:fireTime];
    [mTransientObjects addObject:aBullet];

    [aBullet release];
}

// myGameLoop is called via the timer above firing at whatever interval makes sense for your game
- (void) myGameLoop {

switch (gameState) {
    case PLAYING:
        for (nextObject in mTransientObjects)
            [nextObject updateYourself:gameTime];

        // Now check for dead object, add explosions to mTransientObjects
        // Remove dead things, add anything new etc.
            etc.
}

// implementation in Bullet subclass
// Bullet is SubClass of your overall Sprite class
- (void) updateYourself:(NSTimerInterval) timeInterval  {
// Do any movement, change of animation frame, start sound....etc. etc.
}
相关问题