曾经,微信里面可以玩一个打飞机的小游戏,很有趣,后来又没有了,这里基于原版素材写了一个高仿微信打飞机的小游戏
环境
游戏主菜单界面,进入游戏的入口界面
bool MainMenuScene::init()
{
//
// 1. super init first
if ( !Scene::init() )
{
return false;
}
auto visible_size = Director::getInstance()->getVisibleSize();
auto visible_origin = Director::getInstance()->getVisibleOrigin();
// 添加背景图
Sprite* background = Sprite::create("img/background.png");
background->setContentSize(visible_size);
background->setPosition(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2);
addChild(background);
Sprite* title = Sprite::create("img/title.png");
title->setScale(1.5); // 尺寸适当调整
title->setPosition(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2 + 40);
addChild(title);
// 添加按钮
Button* start_btn = Button::create("img/game_resume_nor.png", "img/game_resume_pressed.png", "img/game_resume_nor.png"); // 指定好各种状态图的按钮
start_btn->setScale(1.5); // 尺寸适当调整
start_btn->setPosition(Vec2(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2));
start_btn->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type){
// 按钮点击事件
switch (type)
{
case ui::Widget::TouchEventType::BEGAN:
// 播放音效
SimpleAudioEngine::getInstance()->playEffect("sound/button.wav");
break;
case ui::Widget::TouchEventType::ENDED:
{
// 切换到主游戏场景
auto game_scene = GameScene::createScene();
TransitionScene* transition_scene = TransitionFade::create(0.5, game_scene);
Director::getInstance()->replaceScene(transition_scene);
}
break;
default:
break;
}
});
addChild(start_btn);
return true;
}
游戏场景就是主要的游戏逻辑,控制玩家飞机发射子弹攻击敌机,拾取道具等
在场景中,玩家、敌机、子弹、道具、天空背景都是不同的对象,分别具有不同的行为
玩家
class Player : public cocos2d::Sprite
{
public:
virtual bool init();
CREATE_FUNC(Player);
public:
Bullet* shootSingle(); // 射击一次,产生一颗子弹
cocos2d::Vector<Bullet*> shootDouble(); // 射击一次,产生双子弹
void fetchWeapon(WeaponType weapon_type); // 拾取道具
void destroy(); // 玩家over
BulletType m_bullet_type; // 根据子弹类型改变子弹
};
子弹
enum BulletType
{
BASE, // 单子弹
POWER // 双子单
};
class Bullet : public cocos2d::Sprite
{
public:
virtual bool init();
void initWithType(BulletType bullet_type); // 根据子弹类型设置纹理
CREATE_FUNC(Bullet);
void pauseMove();
void resumeMove();
public:
int m_kill_hp; // 子弹的杀伤力
bool m_hit_flag; // 标记子弹是否已击中
private:
void move(float tm);
float m_speed;
};
敌机
enum EnemyType
{
SMALL, // 小飞机
MEDIUM, // 中等飞机
BIG // 大飞船
};
class Enemy : public cocos2d::Sprite
{
public:
virtual bool init();
CREATE_FUNC(Enemy);
void pauseMove();
void resumeMove();
void initWithType(EnemyType enemy_type);
void move(float tm);
void hit(int reduce_hp); // 敌机被子弹打中
void die(); // 敌机死亡
int m_hp; // 敌机总血量
EnemyType m_type;
private:
float m_speed;
};
道具
enum WeaponType
{
AMMO,
BOMB
};
class Weapon : public cocos2d::Sprite
{
public:
virtual bool init();
CREATE_FUNC(Weapon);
void initWithType(WeaponType weapon_type);
void pauseMove();
void resumeMove();
WeaponType m_type;
private:
void move(float tm);
};
天空背景实际上只有一张图,构造两张图循环移动,产生天空无限移动的效果
bool SkyBackground::init()
{
if (!Node::init())
return false;
Size visible_size = Director::getInstance()->getVisibleSize();
Point visible_origin = Director::getInstance()->getVisibleOrigin();
// 增加两张背景图,循环交替,构造连续滚动效果
m_background1 = Sprite::create("img/background.png");
m_background1->setContentSize(visible_size); // 与屏幕适应
m_background1->setAnchorPoint(Point::ZERO); // 锚点设为左下坐标点,方便计算
m_background1->setPosition(visible_origin); // 一定要设置初始位置
addChild(m_background1);
m_background2 = Sprite::create("img/background.png");
m_background2->setContentSize(visible_size);
m_background2->setAnchorPoint(Point::ZERO);
m_background2->setPosition(visible_origin.x, visible_origin.y + visible_size.height);
addChild(m_background2);
// 调度两张图的移动
schedule(schedule_selector(SkyBackground::backgroundRotate), kFrameUpdateInterval); // delta time smaller, move more smooth
return true;
}
void SkyBackground::backgroundRotate(float tm)
{
Size visible_size = Director::getInstance()->getVisibleSize();
Point visible_origin = Director::getInstance()->getVisibleOrigin();
// 背景2在背景1上方无缝衔接,当背景2到达底部时候,将背景1重新归位
m_background1->setPositionY(m_background1->getPositionY() - 0.3); // rotate speed
m_background2->setPositionY(m_background1->getPositionY() + visible_size.height);
if (m_background2->getPositionY() <= visible_origin.y)
m_background1->setPositionY(visible_origin.y);
}
玩家飞机根据触摸移动进行相应的移动
bool GameScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
if (m_is_over)
return true;
CCLOG("onTouchBegan");
m_pretouch_pos = touch->getLocation();
m_preplayer_pos = m_player->getPosition();
return true;
}
void GameScene::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event)
{
if (m_is_over)
return;
CCLOG("onTouchMoved");
Point current_touch_pos = touch->getLocation();
Vec2 move_delta = current_touch_pos - m_pretouch_pos;
m_player->setPosition(m_preplayer_pos + move_delta);
}
void GameScene::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
if (m_is_over)
return;
CCLOG("onTouchEnded");
m_pretouch_pos = kInitPoint;
}
Bullet* Player::shootSingle()
{
// 发射子弹音效
SimpleAudioEngine::getInstance()->playEffect("sound/bullet.wav");
// 子弹从飞机头部打出来
Bullet* bullet = Bullet::create();
bullet->initWithType(BulletType::BASE);
bullet->setPosition(getPositionX(), getPositionY() + getContentSize().height / 2);
return bullet;
}
Vector<Bullet*> Player::shootDouble()
{
// 发射子弹音效
SimpleAudioEngine::getInstance()->playEffect("sound/bullet.wav");
Vector<Bullet*> double_bullets;
// 子弹都从飞机头部打出来,左右两个子弹分布在机头
Bullet* bullet_left = Bullet::create();
bullet_left->initWithType(BulletType::POWER);
bullet_left->setPosition(getPositionX() - getContentSize().width / 4, getPositionY() + getContentSize().height / 2);
double_bullets.pushBack(bullet_left);
Bullet* bullet_right = Bullet::create();
bullet_right->initWithType(BulletType::POWER);
bullet_right->setPosition(getPositionX() + getContentSize().width / 4, getPositionY() + getContentSize().height / 2);
double_bullets.pushBack(bullet_right);
return double_bullets;
}
void Player::fetchWeapon(WeaponType weapon_type)
{
// 如果道具是子弹,且之前是单子弹,切换子弹,并持续一段时间
if (m_bullet_type == BulletType::BASE && weapon_type == WeaponType::AMMO)
{
m_bullet_type = BulletType::POWER;
// 播放音效
SimpleAudioEngine::getInstance()->playEffect("sound/get_double_laser.wav");
// 子弹有效时间,用lambda做单次定时器回调
scheduleOnce([&](float delay){
m_bullet_type = BulletType::BASE;
SimpleAudioEngine::getInstance()->playEffect("sound/out_porp.wav");
}, kPowerTime, "power_status");
}
else if (weapon_type == WeaponType::BOMB)
{
// 播放音效
SimpleAudioEngine::getInstance()->playEffect("sound/get_bomb");
// TODO: 储存炸弹
}
}
子弹是由场景通过定时器调度的,每次固定时间间隔根据当前玩家的子弹类型生成新的子弹
void GameScene::generateBullet(float interval)
{
if (m_is_over)
return;
// 由定时器触发产生子弹,也可以由某个按键触发
// 根据玩家子弹状态产生不同的子弹,加到场景和管理器
if (m_player->m_bullet_type == BulletType::BASE)
{
Bullet* bullet = m_player->shootSingle();
addChild(bullet, kBattleZorder);
m_bullets.pushBack(bullet);
}
else if (m_player->m_bullet_type == BulletType::POWER)
{
Vector<Bullet*> double_bullets = m_player->shootDouble();
for (Bullet* bullet : double_bullets)
{
addChild(bullet, kBattleZorder);
m_bullets.pushBack(bullet);
}
}
}
敌机会随机从顶部生成出来,也是由定时器调度
void GameScene::generateEnemy(float interval)
{
if (m_is_over)
return;
Size visible_size = Director::getInstance()->getVisibleSize();
Point visible_origin = Director::getInstance()->getVisibleOrigin();
// 定时器触发产生道具,根据概率生成不同类型
// 加载到场景和管理器
EnemyType enemy_type;
float random_factor = CCRANDOM_0_1();
if (random_factor >= 0.9)
enemy_type = EnemyType::BIG;
else if (random_factor >= 0.6 && random_factor < 0.9)
enemy_type = EnemyType::MEDIUM;
else
enemy_type = EnemyType::SMALL;
Enemy* enemy = Enemy::create();
enemy->initWithType(enemy_type);
// 生成随机位置,但要保证敌机显示完整,所以左右各留出半个敌机身位
float random_x = enemy->getContentSize().width / 2 +
(visible_size.width - enemy->getContentSize().width) * CCRANDOM_0_1();
enemy->setPosition(visible_origin.x + random_x,
visible_origin.y + visible_size.height + enemy->getContentSize().height / 2);
addChild(enemy, kBattleZorder);
m_enemies.pushBack(enemy);
}
道具有子弹和炸弹两种,由定时器调度
判断敌机是否死亡、道具拾取、玩家是否被摧毁都要做碰撞检测
// --- 碰撞监测 ---
// 判断玩家
for (Enemy* enemy : m_enemies)
{
if (enemy->m_hp > 0 && enemy->getBoundingBox().intersectsRect(m_player->getBoundingBox()))
{
// 玩家飞机撞了
m_is_over = true;
m_player->destroy();
// 游戏结束,处理后续(延迟等到玩家飞机t摧毁动画结束)
scheduleOnce([&](float delay){
gameOver();
}, 2.0, "game over");
return;
}
}
// 判断敌机被子弹击中
Vector<Bullet*> hit_bullets;
for (Bullet* bullet : m_bullets)
{
for (Enemy* enemy : m_enemies)
{
// 注意,某个子弹撞击了后要消失,并且不可再参与碰撞检测
if (!bullet->m_hit_flag
&& enemy->m_hp > 0
&& bullet->getBoundingBox().intersectsRect(enemy->getBoundingBox()))
{
enemy->hit(bullet->m_kill_hp);
if (enemy->m_hp <= 0)
{
// 先更新分数,再移除飞机
getScore(enemy->m_type);
enemy->die(); // 这里面做了对象销毁
m_enemies.eraseObject(enemy); // 这里可以先于动画放完就移出管理器
}
// 移除子弹, 先标记起来放到移除列表
bullet->m_hit_flag = true;
hit_bullets.pushBack(bullet);
}
}
}
// 这里统一移除子弹,避免边判断边移除导致的内存问题
for (Bullet* bullet : hit_bullets)
{
m_bullets.eraseObject(bullet);
bullet->removeFromParent();
}
hit_bullets.clear();
// 判断拾取道具
for (Weapon* weapon : m_weapons)
{
if (weapon->getBoundingBox().intersectsRect(m_player->getBoundingBox()))
{
if (weapon->m_type == WeaponType::AMMO)
m_player->fetchWeapon(WeaponType::AMMO);
else if (weapon->m_type == WeaponType::BOMB)
{
// 炸掉所有敌机
SimpleAudioEngine::getInstance()->playEffect("sound/use_bomb.wav");
CCLOG("before bomb enemy number = %d", m_enemies.size());
for (Enemy* enemy : m_enemies)
{
// 先更新分数,再移除飞机
getScore(enemy->m_type);
enemy->m_hp = 0; // 先把血量置空
enemy->die(); // 这里面做了对象销毁
}
m_enemies.clear(); // 一定要放在这里统一清空
CCLOG("after bomb enemy number = %d", m_enemies.size());
}
// 道具本身也要消失
m_weapons.eraseObject(weapon);
weapon->removeFromParent();
}
}
场景里看不见的元素需要销毁做内存回收
// --- 元素管理 ---
for (Bullet* bullet : m_bullets)
{
// 若飞行的子弹出了屏幕,则移除
if (bullet->getPositionY() > visible_origin.y +
visible_size.height + bullet->getContentSize().height / 2)
{
m_bullets.eraseObject(bullet); // erase from vector should before itself cleanup
bullet->removeFromParent();
}
}
CCLOG("current bullets count: %d", m_bullets.size());
for (Enemy* enemy : m_enemies)
{
// 若存活敌机出了平面,则移除
if (enemy->getPositionY() < visible_origin.y - enemy->getContentSize().height / 2)
{
m_enemies.eraseObject(enemy);
enemy->removeFromParent();
}
}
CCLOG("alive enemy count: %d", m_enemies.size());
for (Weapon* weapon : m_weapons)
{
// 若未拾取的道具出了屏幕,则移除
if (weapon->getPositionY() < visible_origin.y - weapon->getContentSize().height / 2)
{
m_weapons.eraseObject(weapon);
weapon->removeFromParent();
}
}
CCLOG("unfetched weapon count: %d", m_weapons.size());
在摧毁敌机或者炸掉敌机时都要更新游戏分数
void GameScene::getScore(EnemyType enemy_type)
{
// 根据不同敌机类别得不同分数
static int phase = 0;
switch (enemy_type)
{
case EnemyType::SMALL:
m_score += kSmallPlaneScore;
break;
case EnemyType::MEDIUM:
m_score += kMediumPlaneScore;
break;
case EnemyType::BIG:
m_score += kBigPlaneScore;
break;
default:
break;
}
// 如果分数达到一定阶段,播放成就音效
int new_phase = m_score / kAchievementScoreUnit;
if (new_phase > phase)
{
SimpleAudioEngine::getInstance()->playEffect("sound/achievement.wav");
phase = new_phase;
}
// 刷新UI
m_score_label->setString(__String::createWithFormat("score: %d", m_score)->_string);
// m_score_label->setString(StringUtils::format("score: %d", m_score)); // the same
}
游戏结束、暂停、恢复
void GameScene::gameOver()
{
CCLOG("player hit, game over");
Size visible_size = Director::getInstance()->getVisibleSize();
Point visible_origin = Director::getInstance()->getVisibleOrigin();
// 停止背景音乐
// FIXME: stop background music may cause crash
if (SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying())
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
// 停止所有的调度器
unschedule(schedule_selector(GameScene::generateEnemy));
unschedule(schedule_selector(GameScene::generateWeapon));
unschedule(schedule_selector(GameScene::generateBullet));
// 添加结束画面
Sprite* game_over_background = Sprite::create("img/gameover.png");
game_over_background->setContentSize(visible_size);
game_over_background->setAnchorPoint(Point::ZERO);
game_over_background->setPosition(visible_origin);
addChild(game_over_background, kGameoverZorder);
Label* final_score_label = Label::createWithTTF(std::to_string(m_score), "fonts/Marker Felt.ttf", 14);
final_score_label->setColor(Color3B::BLACK);
final_score_label->setPosition(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2);
addChild(final_score_label, kGameoverZorder);
// 重新开始按钮
Button* restart_btn = Button::create("img/restart.png"); // 只添加一张背景图按钮
restart_btn->setScale(1.5);
restart_btn->setPosition(Vec2(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2 - 30));
restart_btn->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type){
// 按钮点击事件
switch (type)
{
case ui::Widget::TouchEventType::BEGAN:
// 播放音效
SimpleAudioEngine::getInstance()->playEffect("sound/button.wav");
break;
case ui::Widget::TouchEventType::ENDED:
{
// 重载主游戏场景
auto game_scene = GameScene::createScene();
TransitionScene* transition_scene = TransitionFade::create(0.5, game_scene);
Director::getInstance()->replaceScene(transition_scene);
}
break;
default:
break;
}
});
addChild(restart_btn, kGameoverZorder);
// 结束游戏按钮
Button* quit_btn = Button::create("img/quit.png"); // 只添加一张背景图按钮
quit_btn->setScale(1.5);
quit_btn->setPosition(Vec2(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2 - 60));
quit_btn->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type){
// 按钮点击事件
switch (type)
{
case ui::Widget::TouchEventType::BEGAN:
// 播放音效
SimpleAudioEngine::getInstance()->playEffect("sound/button.wav");
break;
case ui::Widget::TouchEventType::ENDED:
{
// 返回到菜单场景
auto main_menu_scene = MainMenuScene::createScene();
TransitionScene* transition_scene = TransitionFade::create(0.5, main_menu_scene);
Director::getInstance()->replaceScene(main_menu_scene);
}
break;
default:
break;
}
});
addChild(quit_btn, kGameoverZorder);
}
void GameScene::gamePause()
{
// 暂停背景音乐
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
// 暂停游戏标志
m_is_pause = true;
// 暂停所有调度器
unschedule(schedule_selector(GameScene::generateEnemy));
unschedule(schedule_selector(GameScene::generateWeapon));
unschedule(schedule_selector(GameScene::generateBullet));
// 暂停所有的元素移动
m_sky_background->pauseRotate();
for (Enemy* enemy : m_enemies)
enemy->pauseMove();
for (Bullet* bullet : m_bullets)
bullet->pauseMove();
for (Weapon* weapon : m_weapons)
weapon->pauseMove();
}
void GameScene::gameResume()
{
// 恢复背景音乐
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
// 恢复游戏标志
m_is_pause = false;
// 恢复所有调度器
schedule(schedule_selector(GameScene::generateEnemy), kEnemyGenerateInterval);
schedule(schedule_selector(GameScene::generateWeapon), kWeaponGenerateInterval);
schedule(schedule_selector(GameScene::generateBullet), kBulletGenerateInterval);
// 恢复所有的元素移动
m_sky_background->resumeRotate();
for (Enemy* enemy : m_enemies)
enemy->resumeMove();
for (Bullet* bullet : m_bullets)
bullet->resumeMove();
for (Weapon* weapon : m_weapons)
weapon->resumeMove();
}
csdn:飞机大战
github:飞机大战