这个游戏是关于一个球随机在屏幕上移动,可以用手指来操纵令一个球,如果两个球碰撞到一起,就表示输了,非常简单的一个游戏
在StoryBoard里定义两个UIImageView和一个start按钮
然后把这两个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);
如果点击了start按钮
- (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]; } }
代码可以在下载
IOS的一个关于球碰撞的小游戏
时间: 2024-10-05 23:43:05