一、小鸟的状态

typedef enum{
ACTION_STATE_IDLE, //准备状态
ACTION_STATE_FLY, //飞行状态
ACTION_STATE_DIE //死亡状态
} ActionState;

二、小鸟相关操作

1、初始化随机创建一种颜色的鸟createBirdByRandom

2、小鸟状态的切换changeState

3、创建小鸟的动画createAnimation

三、3种不同状态的分析

初始化时创建了小鸟的2个动作

翅膀的挥动idleAction

小鸟的上下移动swingAction

// init idle status
//create the bird animation
Animation* animation = this->createAnimation(this->birdNameFormat.c_str(), 3, 10);
Animate* animate = Animate::create(animation);
this->idleAction = RepeatForever::create(animate);
// create the swing action
ActionInterval *up = CCMoveBy::create(0.4f,Point(0, 8));
ActionInterval *upBack= up->reverse();
this->swingAction = RepeatForever::create(Sequence::create(up, upBack, NULL));
1、idle空闲状态

void BirdSprite::idle() {
if (changeState(ACTION_STATE_IDLE)) {
this->runAction(idleAction);
this->runAction(swingAction);
}
}
2、fly飞行状态

点击开始按钮,游戏开始后,小鸟由idle状态切换到fly状态

由于游戏用到了box2d物理引擎,所以fly状态除了挥动翅膀还要受到重力的作用

void BirdSprite::fly() {
if(changeState(ACTION_STATE_FLY)) {
this->stopAction(swingAction);
this->getPhysicsBody()->setGravityEnable(true);
}
}
3、die死亡状态

当小鸟碰到水管后,进入死亡状态

void BirdSprite::die() {
if(changeState(ACTION_STATE_DIE)) {
this->stopAllActions();
}
}

项目源码托管在Github:https://github.com/smiger/FlappyBird​