小时候红白机上玩的的经典90坦克,看起来简单,做起来其实有点复杂,这里用原版素材还原了一个简版
对于图片,音乐,动画提前做缓存,提高后面使用效率
// 预加载资源(暂且使用同步模式)
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("img/tank/tank.plist", "img/tank/tank.png");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("img/item/item.plist", "img/item/item.png");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("img/tank/blast.plist", "img/tank/blast/blast.png");
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/levelstarting.wav");
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/gamewin.wav");
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/gameover.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/bonus.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/brickhit.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/eexplosion.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/fexplosion.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/ice.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/life.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/moving.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/nmoving.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/shieldhit.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/shoot.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/steelhit.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/tbonushit.wav");
Animation* player_born_animation = Animation::create();
player_born_animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("shield1.png"));
player_born_animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("shield2.png"));
player_born_animation->setDelayPerUnit(0.2);
AnimationCache::getInstance()->addAnimation(player_born_animation, "player_born_animation");
Animation* enemy_born_animation = Animation::create();
for (int i = 1; i <= 4; i++)
enemy_born_animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("born" + std::to_string(i) + ".png"));
enemy_born_animation->setDelayPerUnit(0.2);
AnimationCache::getInstance()->addAnimation(enemy_born_animation, "enemy_born_animation");
场景中地图、坦克、子弹、道具都是子元素,每个元素都有对应的行为和状态
地图是由tmx文件导入的,提前在tiled编辑器里导出,每个方格是地图块的最小单位
方格类型包括:
不同方格属性不同,比如是否能让坦克通过,是否可以被子弹破坏
// 加载游戏地图(tile地图必须保证tmx文件跟图片资源相对目录)
std::string map_name = "img/map/Round" + std::to_string(round) + ".tmx";
initWithTMXFile(map_name);
// tile_map->setScale(kScaleFactor); // this works to make map looks bigger
// print map info
Size map_size = getContentSize();
Size map_array = getMapSize();
// tmx地图的方格必须用行列值重新计算,getTileSize()是不准确的
Size tile_size = Size(map_size.width / map_array.width, map_size.height / map_array.height);
由于地图加载场景中,尺寸大小会有缩放,所以需要精确计算每个方块的大小
class Player : public Sprite
{
public:
virtual bool init();
CREATE_FUNC(Player);
public:
void initWithType(PlayerType player_type);
void setGameScene(GameScene* game_scene);
void move(float tm);
Bullet* shootSingle(); // 射击一次,产生一颗子弹
Vector<Bullet*> shootDouble(); // 射击一次,产生双子弹
void fetchItem(ItemType item_type); // 拾取道具
void destroy(); // 玩家over
public:
void setSize(Size size);
void setDirection(JoyDirection direction);
JoyDirection m_head_direction; // 坦克朝向
float m_bullet_interval;
bool m_moving;
PlayerStatus m_status;
PlayerWeapon m_weapon;
private:
GameScene* m_game_scene = nullptr; // like callback
Size m_size;
};
enum EnemyType
{
NORMAL, // 普通坦克
ARMOR, // 装甲车
SPEED // 迅捷坦克
};
enum EnemyStatus
{
ESIMPLE, // 普通
ESHIELD // 无敌
};
class Enemy : public Sprite
{
public:
virtual bool init();
CREATE_FUNC(Enemy);
void initWithType(EnemyType enemy_type);
void setSize(Size size);
public:
void setDirection(JoyDirection direction);
JoyDirection m_head_direction;
void move(float tm);
void changeDirection();
Bullet* shoot();
void hit();
void die();
int m_life;
EnemyType m_type;
bool m_moving;
EnemyStatus m_status;
private:
Size m_size;
float m_speed;
};
enum BulletType
{
BASE, // 单子弹
POWER // 双子单
};
class Bullet : public cocos2d::Sprite
{
public:
virtual bool init();
void initWithDirection(JoyDirection direction, BulletType bullet_type = BASE); // 初始化方向和纹理
CREATE_FUNC(Bullet);
public:
BulletType m_type; // 子弹类型
bool m_hit_flag; // 标记子弹是否已击中
private:
void move(float tm);
JoyDirection m_direction;
};
enum ItemType
{
ACTIVE, // 帽子
STAR, // 火力星
BOMB, // 炸弹
SHOVEL, // 铲子
CLOCK, // 定时
MINITANK // 命
};
class Item : public Sprite
{
public:
virtual bool init();
CREATE_FUNC(Item);
void initWithType(ItemType item_type);
public:
ItemType m_type;
};
专门实现了一个摇杆和射击的中间控制层,通过回调函数的方式施加于游戏场景,其中摇杆控制是稍微复杂一点的
基本思路:确定好摇杆中心的情况下,通过三角函数关系计算跟随触点与坐标横轴的角度,根据角度范围划分具体的方向,另外,在判定射击的时候要处理好左右屏和触摸先后的顺序
// 获取以p1为圆心,p2p1与x轴正方向的弧度值
float Joypad::calcRad(Point p1, Point p2)
{
float xx = p2.x - p1.x;
float yy = p2.y - p1.y;
// 斜边
float xie = sqrt(pow(xx, 2) + pow(yy, 2));
// yy >= 0 弧度在于 0 到 π 之间。(0~180°)
// yy < 0 弧度在于 π 到 2π 之间。(180°~360°)
float rad = yy >= 0 ? (acos(xx / xie)) : (PI * 2 - acos(xx / xie));
return rad;
}
// 得到与角度对应的半径为R的圆上一坐标点, 相对值
Vec2 Joypad::getAnglePosition(float R, float rad)
{
return Point(R * cos(rad), R * sin(rad));
}
void Joypad::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
// CCLOG("onTouchMoved");
if (!m_can_move)
return;
Point visible_origin = Director::getInstance()->getVisibleOrigin();
Size visible_size = Director::getInstance()->getVisibleSize();
// 某一时刻可能是一个或两个触点
Point point1 = touches.front()->getLocation();
Point point2 = touches.back()->getLocation();
Point wheel_center = m_wheel->getPosition();
float wheel_radius = m_wheel->getContentSize().width / 2;
// float stick_radius = m_stick->getContentSize().width / 2;
// 区分左右触点,可能是同一个
Point left_point;
Point right_point;
if (point1.x < point2.x)
{
left_point = point1;
right_point = point2;
}
else
{
left_point = point2;
right_point = point1;
}
// 只有左触点在左半边屏才判断摇杆
if (left_point.x < visible_origin.x + visible_size.width / 2)
{
Point point = left_point;
// 判断两个圆心的距离是否大于外圈半径
float distance = sqrt(pow(point.x - wheel_center.x, 2) + pow(point.y - wheel_center.y, 2));
float rad = calcRad(wheel_center, point);
if (distance >= wheel_radius)
{
// 摇杆中心不超出外圈范围
m_stick->setPosition(wheel_center + getAnglePosition(wheel_radius, rad));
}
else
m_stick->setPosition(point); // 摇杆跟随触点
// 换算成角度,根据键类型确定方向,将方向控制信号传给游戏场景
float angle = rad * 180.0 / PI;
if (m_type == KEY4)
{
// 加入控制死区,只有圆心偏移距离够长才换方向
JoyDirection direction;
if (distance >= wheel_radius / 5)
{
// 靠近轴90度范围
if ((angle >= 0 && angle < 45) || (angle >= 315 && angle < 360))
direction = RIGHT; // 右
else if (angle >= 45 && angle < 135)
direction = UP; // 上
else if (angle >= 135 && angle < 225)
direction = LEFT; // 左
else if (angle >= 225 && angle < 315)
direction = DOWN; // 下
}
else
direction = NONE;
// callback
if (m_game_scene)
m_game_scene->onEnumDirection(direction);
}
else if (m_type == KEY8)
{
// 加入控制死区,只有圆心偏移距离够长才换方向
JoyDirection direction;
if (distance >= wheel_radius / 5)
{
// 靠近轴45度范围
if ((angle >= 0 && angle < 22.5) || (angle >= 337.5 && angle < 360))
direction = RIGHT; // 右
else if (angle >= 22.5 && angle < 67.5)
direction = RIGHT_UP; // 右上
else if (angle >= 67.5 && angle < 112.5)
direction = UP; // 上
else if (angle >= 112.5 && angle < 157.5)
direction = LEFT_UP; // 左上
else if (angle >= 157.5 && angle < 202.5)
direction = LEFT; // 左
else if (angle >= 202.5 && angle < 247.5)
direction = LEFT_DOWN; // 左下
else if (angle >= 247.5 && angle < 292.5)
direction = DOWN; // 下
else if (angle >= 292.5 && angle < 337.5)
direction = RIGHT_DOWN; // 右下
}
else
direction = NONE;
// callback
if (m_game_scene)
m_game_scene->onEnumDirection(direction);
}
else if (m_type == KEYANY)
{
// callback
if (m_game_scene)
m_game_scene->onAngleDirection(angle);
}
}
}
玩家控制包括方向键移动和开火射击
void GameScene::onEnumDirection(JoyDirection direction)
{
// CCLOG("GameScene onEnumDirection: %d", direction);
static JoyDirection pre_direction = NONE;
// 只有方向改变时才给玩家坦克发控制指令
if (direction != pre_direction)
{
// TODO: 每次重置为最近的整点方块中心位置,减少被卡住的概率
m_player1->setDirection(direction);
pre_direction = direction;
}
}
void GameScene::onFireBtn(bool is_pressed)
{
// CCLOG("GameScene onFireBtn: %s", is_pressed ? "yes" : "no");
static bool pre_press_status = false;
if (is_pressed != pre_press_status)
{
// 调度子弹,同时考虑单发和i连发
if (is_pressed)
{
// TODO: every moment make sure only limit number bullets in the screen
// FIXME: timer would wait at least one delay interval, here shoot a bullet at one btn click
if (m_player_bullets.empty())
{
if (m_player1->m_weapon == SINGLE_GUN)
{
Bullet* bullet = m_player1->shootSingle();
addChild(bullet, kMapZorder);
m_player_bullets.pushBack(bullet);
}
else if (m_player1->m_weapon == DOUBLE_GUN)
{
Vector<Bullet*> double_bullets = m_player1->shootDouble();
for (Bullet* bullet : double_bullets)
{
addChild(bullet, kMapZorder);
m_player_bullets.pushBack(bullet);
}
}
}
schedule(schedule_selector(GameScene::emitPlayerBullet), m_player1->m_bullet_interval);
}
else
unschedule(schedule_selector(GameScene::emitPlayerBullet));
pre_press_status = is_pressed;
}
}
以上是游戏场景的几个回调函数,供摇杆类调用控制玩家
敌方坦克随机出现在地图上方出生点,随机切换方向,随机开火,同一批次生成的坦克有数量限制,总坦克数量有限制
void GameScene::generateEnemy(float tm)
{
// 最后剩下的则停掉坦克生成
if (m_enemies.size() == m_enemy_count)
{
unschedule(schedule_selector(GameScene::generateEnemy));
return;
}
// 当前还有完整的一批,则不产生
if (m_enemies.size() >= kEnemyBatchTankCount)
return;
Size map_size = m_battle_field->getContentSize();
Size map_array = m_battle_field->getMapSize();
// tmx地图的方格必须用行列值重新计算,getTileSize()是不准确的
Size tile_size = Size(map_size.width / map_array.width, map_size.height / map_array.height);
// 根据概率生成敌方坦克
float tank_type_factor = CCRANDOM_0_1();
EnemyType enemy_type;
if (tank_type_factor < 0.6)
enemy_type = NORMAL;
else if (tank_type_factor >= 0.6 && tank_type_factor < 0.9)
enemy_type = ARMOR;
else
enemy_type = SPEED;
Enemy* enemy = Enemy::create();
enemy->initWithType(enemy_type);
enemy->setSize(tile_size * 2 * kTankSizeFactor);
// 随机生成位置,顶部三个空位
float tank_pos_factor = CCRANDOM_0_1();
if (tank_pos_factor <= 1.0 / 3)
enemy->setPosition(m_battle_field->getPositionX() + tile_size.width,
m_battle_field->getPositionY() + map_size.height - tile_size.height);
else if (tank_pos_factor >= 1.0 / 3 && tank_pos_factor < 2.0 / 3)
enemy->setPosition(m_battle_field->getPositionX() + map_size.width / 2,
m_battle_field->getPositionY() + map_size.height - tile_size.height);
else
enemy->setPosition(m_battle_field->getPositionX() + map_size.width - tile_size.width,
m_battle_field->getPositionY() + map_size.height - tile_size.height);
// 随机生成方向
float tank_direction_factor = CCRANDOM_0_1();
if (tank_direction_factor < 0.25)
enemy->setDirection(UP);
else if (tank_direction_factor >= 0.25 && tank_direction_factor < 0.5)
enemy->setDirection(DOWN);
else if (tank_direction_factor >= 0.5 && tank_direction_factor < 0.75)
enemy->setDirection(LEFT);
else
enemy->setDirection(RIGHT);
// 根据定时决定初始是否可以移动
if (m_is_clock)
enemy->m_moving = false;
addChild(enemy, kMapZorder);
m_enemies.pushBack(enemy);
}
子弹实际是由玩家或地方坦克射击产生的,但是需要在场景中调度
void GameScene::emitPlayerBullet(float tm)
{
// 小技巧,如果子弹消失了则快速发射一颗,所以子弹发射频率会随着碰撞调整
if (m_player_bullets.empty())
{
if (m_player1->m_weapon == SINGLE_GUN)
{
Bullet* bullet = m_player1->shootSingle();
addChild(bullet, kMapZorder);
m_player_bullets.pushBack(bullet);
}
else if (m_player1->m_weapon == DOUBLE_GUN)
{
Vector<Bullet*> double_bullets = m_player1->shootDouble();
for (Bullet* bullet : double_bullets)
{
addChild(bullet, kMapZorder);
m_player_bullets.pushBack(bullet);
}
}
}
}
void GameScene::emitEnemyBullet(float tm)
{
for (Enemy* enemy : m_enemies)
{
// 不同的敌人坦克根据类型,发射子弹频率不同
float enemy_shoot_factor = CCRANDOM_0_1();
if (enemy->m_type == NORMAL && enemy_shoot_factor >= 0.5
|| enemy->m_type == ARMOR && enemy_shoot_factor >= 0.2
|| enemy->m_type == SPEED && enemy_shoot_factor >= 0.7)
{
Bullet* bullet = enemy->shoot();
addChild(bullet, kMapZorder);
m_enemy_bullets.pushBack(bullet);
}
}
}
道具是玩家射击到装甲车地方坦克时,根据概率随机选择类型出现在地图任意位置
void GameScene::generateItem()
{
SimpleAudioEngine::getInstance()->playEffect("sound/tbonushit.wav");
Size map_size = m_battle_field->getContentSize();
Size map_array = m_battle_field->getMapSize();
// tmx地图的方格必须用行列值重新计算,getTileSize()是不准确的
Size tile_size = Size(map_size.width / map_array.width, map_size.height / map_array.height);
// 随机类型
ItemType item_type;
float item_type_factor = CCRANDOM_0_1();
if (item_type_factor < 1.0 / 6)
item_type = ACTIVE;
else if (item_type_factor >= 1.0 / 6 && item_type_factor < 2.0 / 6)
item_type = STAR;
else if (item_type_factor >= 2.0 / 6 && item_type_factor < 3.0 / 6)
item_type = BOMB;
else if (item_type_factor >= 3.0 / 6 && item_type_factor < 4.0 / 6)
item_type = SHOVEL;
else if (item_type_factor >= 4.0 / 6 && item_type_factor < 5.0 / 6)
item_type = CLOCK;
else
item_type = MINITANK;
Item* item = Item::create();
item->initWithType(item_type);
// 随机位置
float item_posx_factor = CCRANDOM_0_1();
float pos_x = m_battle_field->getPositionX() + (map_size.width - tile_size.width * 2) * item_posx_factor;
float item_posy_factor = CCRANDOM_0_1();
float pos_y = m_battle_field->getPositionY() + (map_size.height - tile_size.height * 2) * item_posy_factor;
item->setPosition(pos_x, pos_y);
addChild(item, kItemZorder);
m_items.pushBack(item);
}
有多种类型的碰撞检查
具体逻辑都卸载update函数,保证每帧都会检测,及时反映
其中由于需要说明的是,对于地图中不同砖块被子弹碰撞或被坦克碰撞的逻辑,需要根据坐标定位到方块gid号,进而判断类型来做对应的处理,另外如果拾取到铲子道具,需要对地图中土砖变换为钢板,做方块类型的变更
bool isBulletCollide(Rect bounding_box, BulletType bullet_type); // 子弹的碰撞
bool isTankCollide(Rect bounding_box, JoyDirection direction); // 带方向坦克的碰撞
bool isEagleHurt(Rect bounding_box);
void protectEagle(); // 用钢板把老鹰围起来
void unprotectEagle(); // 老鹰恢复为土砖围起来
场景中的元素需要及时的回收和释放,避免内存浪费
如果地方坦克全部被击毁,则游戏胜利;如果玩家坦克命数用完或者总部老鹰被击毁则游戏结束;当前关卡通过后会进入下一关
void GameScene::gameWin()
{
CCLOG("game win");
SimpleAudioEngine::getInstance()->playBackgroundMusic("sound/gamewin.wav", false);
// 切换关卡,通关后从第一关开始
int next_round = m_round + 1; // 关卡提升
if (next_round > kTotalRound)
next_round = 1;
// FIXME: should delay before next round
Scene* scene = GameScene::createScene(next_round);
TransitionScene* transition_scene = TransitionFade::create(0.0, scene);
Director::getInstance()->replaceScene(transition_scene);
}
void GameScene::gameOver()
{
CCLOG("game over");
SimpleAudioEngine::getInstance()->playEffect("sound/gameover.wav", false);
m_is_over = true;
// 游戏结束的标签
Point visible_origin = Director::getInstance()->getVisibleOrigin();
Size visible_size = Director::getInstance()->getVisibleSize();
Label *gameover_label = Label::createWithTTF("game over", "fonts/Marker Felt.ttf", 24);
gameover_label->setColor(Color3B::WHITE);
gameover_label->setPosition(visible_origin.x + visible_size.width / 2,
visible_origin.y - 30);
addChild(gameover_label, kLevelSplashZorder); // 分数浮层在最上方
// 播放动画,飞入画面
auto move_to = MoveTo::create(1.0, Point(visible_origin.x + visible_size.width / 2,
visible_origin.y + visible_size.height / 2));
gameover_label->runAction(move_to);
}
可以考虑扩展成双人联网合作模式
技术实现思路:
csdn:经典坦克
github:经典坦克