憤怒的小鳥這個遊戲非常經典,火了很長一段時間
我們可以不借助第三方庫進行實作,這裡隻是進行了一些簡單的實作
沒有添加碰撞檢測 完成了一些功能 我們點選螢幕小鳥會飛
如果不點選小鳥會落下
這裡用到的技術也很簡單,用到了使用者互動,transform 動畫
#import "BirdViewController.h"
//初速
const float MaxTime = 30;
//加速度 方向向下
const float VG = 0.05;
//初速度
const float MaxV = 2.5;
//初始化總路程
const float AllLength = 692;
typedef enum{
GameStart,
GamePlaying,
GameOver
} GameState;
@interface BirdViewController ()
{
NSTimer *birdTimer;
//開始遊戲開關
BOOL isStart;
//遊戲狀态
GameState gameState;
//小鳥
UIImageView *birdImgView;
UIImageView *birdClotherView;
//總場景
UIView *playLayer;
//跳躍時間
float maxJumpTime;
}
@end
@implementation BirdViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor orangeColor];
[self initBirdAndOther];
birdTimer = [NSTimer scheduledTimerWithTimeInterval:0.008 target:self selector:@selector(update) userInfo:nil repeats:YES];
}
-(void)update
{
//判斷
if (isStart == YES && gameState == GamePlaying)
{
[self updateBird];
}
}
-(void)initBirdAndOther
{
playLayer = [[UIView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:playLayer];
//添加手勢
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(screenTap)];
[self.view addGestureRecognizer:tapGesture];
birdClotherView = (UIImageView *)[[UIView alloc]initWithFrame:CGRectMake(60, 300, 40, 30)];
[playLayer addSubview:birdClotherView];
//初始化小鳥
birdImgView = [[UIImageView alloc] init];
birdImgView.frame = CGRectMake(0, 0, 40, 28);
birdImgView.image = [UIImage imageNamed:@"bird"];
[birdClotherView addSubview:birdImgView];
UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(20, 30, 100, 30);
label.text = @"憤怒的小鳥";
[self.view addSubview:label];
}
-(void)screenTap
{
//每點選一次
maxJumpTime = MaxTime;
if (isStart == NO) {
isStart = YES;
gameState = GamePlaying;
for (UIView *tmp in self.view.subviews) {
[tmp removeFromSuperview];
}
[self initBirdAndOther];
}
CGAffineTransform transform = CGAffineTransformIdentity;
birdImgView.transform = CGAffineTransformRotate(transform, -30 * M_PI / 180 );
}
- (void) updateBird
{
maxJumpTime --;
CGRect rect = birdClotherView.frame;
if (maxJumpTime >= 0)
{
rect.origin.y = rect.origin.y - (MaxV - (MaxTime - maxJumpTime)*VG);
}
else
{
//俯角30度旋轉
CGAffineTransform transform = CGAffineTransformIdentity;
birdImgView.transform = CGAffineTransformRotate(transform, 30 * M_PI / 180 );
rect.origin.y = rect.origin.y - (maxJumpTime*VG);
}
birdClotherView.frame = rect;
}
@end