首页 > 代码库 > IOS的一个关于球碰撞的小游戏

IOS的一个关于球碰撞的小游戏

这个游戏是关于一个球随机在屏幕上移动,能够用手指来操纵令一个球,假设两个球碰撞到一起,就表示输了,很easy的一个游戏

技术分享


在StoryBoard里定义两个UIImageView和一个startbutton

技术分享


然后把这两个UIimageView跟代码链接

@property (weak, nonatomic)IBOutlet UIImageView *player;

@property (weak, nonatomic)IBOutlet UIImageView *enemy;

@property (weak, nonatomic)IBOutlet UIButton *start;


在ViewDidLoad中定义球移动的速率

 pos =CGPointMake(5.0,4.0);

假设点击了startbutton

- (IBAction)start:(id)sender {
    [self.start setHidden:YES];
    //启动一个timer,让player这个球随机移动
    randomMain = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    
    
}

-(void)onTimer{
    [self checkCollision];
    self.enemy.center = CGPointMake(self.enemy.center.x+pos.x, self.enemy.center.y+pos.y);
    if (self.enemy.center.x > 320 || self.enemy.center.x < 0) {
        pos.x = -pos.x;
        
    }
    
    if (self.enemy.center.y > 480 || self.enemy.center.y < 0) {
        pos.y = -pos.y;
    }
}



-(void) checkCollision{
    //检測两个球是否碰撞到一起了
    if (CGRectIntersectsRect(self.player.frame, self.enemy.frame)) {
        [randomMain invalidate];
        [self.start setHidden:NO];
        
        CGRect frame = [self.player frame];
        frame.origin.x = 137.0f;
        frame.origin.y = 326.0f;
        [self.player setFrame:frame];
        
        CGRect frame2 = [self.enemy frame];
        frame2.origin.x = 137.0f;
        frame2.origin.y = 20.0f;
        [self.enemy setFrame:frame2];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ball is catched" message:@"you have to play again" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
        [alert show];
    }
}
代码能够在http://download.csdn.net/detail/baidu_nod/7556833下载

IOS的一个关于球碰撞的小游戏