cocos2d_x_06_游戏_一个都不能死

前端之家收集整理的这篇文章主要介绍了cocos2d_x_06_游戏_一个都不能死前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最终效果图:

环境版本:cocos2d-x-3.3beta0 使用内置的物理引擎

游戏主场景
  1. //
  2. // HeroScene.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8. #ifndef __HeroScene_SCENE_H__
  9. #define __HeroScene_SCENE_H__
  10.  
  11. #include "cocos2d.h"
  12. #include "GameCtrl.h"
  13. // 继承自 有颜色的Layer
  14. class HeroScene : public cocos2d::LayerColor
  15. {
  16. private:
  17. // 屏幕尺寸
  18. Size winSize;
  19. // 数组 不同的层 对应不同的控制器
  20. cocos2d::Vector<GameCtrl*> gameCtrlArr;
  21. public:
  22. // 宏定义的Create方法,内部会调用init方法
  23. CREATE_FUNC(HeroScene);
  24. // 供外界调用的 实例化场景的方法
  25. static cocos2d::Scene* createScene();
  26. // 初始化方法
  27. virtual bool init();
  28. // 时钟方法
  29. // 在场景的时钟方法中,更新\控制 每一个游戏控制器的时钟方法
  30. virtual void update(float dt);
  31. };
  32.  
  33. #endif // __HeroScene_SCENE_H__


  1. //
  2. // HeroScene.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8. #include "HeroScene.h"
  9. #include "GameOverScene.h"
  10.  
  11. USING_NS_CC;
  12. #pragma mark - 生命周期方法
  13. Scene* HeroScene::createScene()
  14. {
  15. // 使用cocos2d 内置的物理引擎
  16. auto scene = Scene::createWithPhysics();
  17. // 显示 调试用的 刚体 边线
  18. // scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
  19. // 调整重力加速度
  20. scene->getPhysicsWorld()->setGravity(Vec2(0,-1000));
  21. // 标准代码 通过静态的create方法创建Layer,添加到场景,并返回场景
  22. auto layer = HeroScene::create();
  23. scene->addChild(layer);
  24. return scene;
  25. }
  26. // 实例化特有的对象
  27. bool HeroScene::init()
  28. {
  29. // 创建一个白色的Layer
  30. if ( !LayerColor::initWithColor(Color4B(255,255,255)) ) return false;
  31. // 屏幕尺寸
  32. winSize = Director::getInstance()->getVisibleSize();
  33. log("winSize:%f,%f",winSize.width,winSize.height);
  34. // 创建2个 GameCtrl (2层)
  35. gameCtrlArr.insert(0,GameCtrl::create(this,30));
  36. if(rand()%2 == 0){
  37. gameCtrlArr.insert(0,250));
  38. }
  39. // 开启消息调度
  40. scheduleUpdate();
  41. // ********************************************
  42. // 物理碰撞检测 「PhysicsContact」
  43. auto listener = EventListenerPhysicsContact::create();
  44. // 开始碰撞 游戏结束
  45. listener->onContactBegin = [this](PhysicsContact & contact){
  46. // 取消 消息调度
  47. this->unscheduleUpdate();
  48. // 切换至Game Over场景
  49. Director::getInstance()->replaceScene(GameOverScene::createScene());
  50. return true;
  51. };
  52. // 向事件分发器,注册listener
  53. Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,this);
  54. // ********************************************
  55. // 用户单点触摸 jump high 【TouchOneByOne】
  56. auto touchListener = EventListenerTouchOneByOne::create();
  57. // 开始触摸 原地 跳一下
  58. touchListener->onTouchBegan = [this](Touch * t,Event * e){
  59. // 每一个游戏控制器 都执行一下 方法
  60. for (auto it = gameCtrlArr.begin(); it!=gameCtrlArr.end(); it++)
  61. {
  62. // 解引用 就可以获得数组成员对象了
  63. // 如果 是点在自己的那一层 才执行 跳高动作
  64. if ((*it)->hitTestPoint(t->getLocation()))
  65. {
  66. (*it)->onUserTouch();
  67. break;
  68. }
  69. }
  70. return false;
  71. };
  72. // 向事件分发器,注册listener
  73. Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(touchListener,this);
  74. return true;
  75. }
  76.  
  77. #pragma mark - 时钟方法
  78. void HeroScene::update(float dt)
  79. {
  80. // 在场景的时钟方法中,更新\控制 每一个游戏控制器的时钟方法
  81. for (auto it = gameCtrlArr.begin(); it!=gameCtrlArr.end(); it++)
  82. {
  83. // 解引用 就可以获得数组成员对象了
  84. // 每一个游戏控制器 开启时钟方法
  85. (*it)->startUpdate(dt);
  86. }
  87. }
  88.  


游戏结束时的场景
  1. //
  2. // GameOverScene.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #include <cocos2d.h>
  10. #include "MainScene.h"
  11. using namespace cocos2d;
  12. // 继承自 有颜色的Layer
  13. class GameOverScene:public LayerColor {
  14. private:
  15. Size winSize;
  16. public:
  17. // 供外界调用
  18. static Scene* createScene()
  19. {
  20. auto s = Scene::create();
  21. auto l = GameOverScene::create();
  22. s->addChild(l);
  23. return s;
  24. };
  25. // 宏定义的Create方法,内部会调用init方法
  26. CREATE_FUNC(GameOverScene);
  27. // 初始化,自己用
  28. virtual bool init()
  29. {
  30. // 父类的init方法
  31. LayerColor::initWithColor(Color4B::WHITE);
  32. // 屏幕大小
  33. winSize = Director::getInstance()->getVisibleSize();
  34. // 创建一个Label
  35. auto label = Label::create();
  36. label->setString("Game Over");
  37. label->setSystemFontSize(40);
  38. label->setName("label");
  39. label->setColor(Color3B::BLACK);
  40. label->setPosition(winSize.width/2,winSize.height/2);
  41. // 添加到Layer
  42. addChild(label);
  43.  
  44. // 添加一个事件,点击 Label,返回到主场景的事件
  45. // 2.触摸Label,开启 时钟updatePosition
  46. // 实例化一个触摸监听器 对象
  47. auto listener = EventListenerTouchOneByOne::create();
  48. // 当触摸开始时,绑定一个闭包函数;
  49. // 【】表示 要传入的外界对象,此处是this
  50. // ()表示参数
  51. listener->onTouchBegan = [this](Touch *t,Event *e){
  52. // 如果 点击 了label,才每隔一秒执行一次 更新位置方法
  53. Label *label =(Label *) e->getCurrentTarget()->getChildByName("label");
  54. if (label->getBoundingBox().containsPoint(t->getLocation())) {
  55. // 回到主场景
  56. // 创建场景,自动释放 it's an autorelease object
  57. auto scene = MainScene::createScene();
  58. // 替换场景
  59. Director::getInstance()->replaceScene(scene);
  60. }
  61. return false;
  62. };
  63. // 5、获取事件分发器,添加一个事件监听器,到this身上;即监听的是this对象【整个图层Layer】
  64. Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,this);
  65. return true;
  66. };
  67. };


一个游戏控制器实例 对应一层子游戏 核心
  1. //
  2. // GameCtrl.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #ifndef ___1_cocos2d_x__GameCtrl__
  10. #define ___1_cocos2d_x__GameCtrl__
  11. #include <cocos2d.h>
  12. // 全屏的边框
  13. #include "Boundary.h"
  14.  
  15. #include "Hero.h"
  16. #include "Block.h"
  17. USING_NS_CC;
  18. // 继承自 Ref,就自动拥有了 释放机制
  19. class GameCtrl:public Ref
  20. {
  21. private:
  22. // 屏幕尺寸
  23. Size winSize;
  24. // 边界 边框,用成员变量记住,是因为 碰撞检测要用到
  25. Boundary * boundary;
  26. Hero * hero;
  27. // 重要~~~Layer就相当于HeroScene场景,因为所有的子精灵 全添加到Layer中,所以需要传入Layer
  28. // 成员变量记住(其他方法中要用到)
  29. Layer * _layer;
  30. float _positionY;
  31. // 临时变量,用于累计 记录 流逝的时间
  32. int tempTimeDelta;
  33. // 总共的时间间隔 (即 时间delta累计到 该间隔时,创建并添加一个障碍物)
  34. int totalIntervalTime;
  35.  
  36. private:
  37. // 每添加一个新的障碍物之后,需重置 用于累计 记录 流逝的时间 的变量
  38. void resetTempTimeDelta();
  39. // 每隔 随机的时间,创建并添加一个障碍物
  40. void addBlock();
  41. public:
  42. // 重要~~~这个Layer就相当于HeroScene场景,所以需要传入Layer
  43. // 参数 就是在屏幕的y值
  44. // 供外界
  45. static GameCtrl* create(Layer *layer,float positionY);
  46. // 自己初始化
  47. virtual bool init(Layer * layer,float positionY);
  48. // 供场景调用,让场景来 开启和关闭 游戏控制器 中的 时钟方法
  49. void startUpdate(float dt);
  50.  
  51. // 当被用户触摸了 时侯调用,给英雄一个向上的速度
  52. void onUserTouch();
  53. bool hitTestPoint(Vec2 point);
  54.  
  55. };
  56.  
  57. #endif /* defined(___1_cocos2d_x__GameCtrl__) */


  1. //
  2. // GameCtrl.cpp
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #include "GameCtrl.h"
  10. // 重要~~~这个Layer就相当于HeroScene场景,所以需要传入Layer
  11. // 参数 就是在屏幕的y值
  12. // 供外界
  13. GameCtrl* GameCtrl::create(cocos2d::Layer *layer,float positionY)
  14. {
  15. auto gameCtrl = new GameCtrl();
  16. // 调用自己的init初始化,将参数 传递过去
  17. gameCtrl->init(layer,positionY);
  18. // 自动释放
  19. gameCtrl->autorelease();
  20. return gameCtrl;
  21. }
  22. // 自己初始化
  23. bool GameCtrl::init(cocos2d::Layer *layer,float positionY)
  24. {
  25. // 成员变量记住,其他方法中 要用到
  26. _layer = layer;
  27. _positionY = positionY;
  28. // 全屏
  29. winSize = Director::getInstance()->getVisibleSize();
  30. //**************************************
  31. // 1、添加游戏的边框、边界
  32. boundary = Boundary::create();
  33. // 居中 (注意 不同的控制器,可能在不同的层 其y值不同 高度也不同)
  34. boundary->setPosition(winSize.width/2,winSize.height/2+positionY);
  35.  
  36. // 全屏
  37. boundary->setContentSize(winSize);
  38. // 添加到Layer
  39. layer->addChild(boundary);
  40. //**************************************
  41. // 2、添加地板 (不需要关联物理世界)
  42. auto ground = Sprite::create();
  43. ground->setColor(Color3B(0,0));
  44. ground->setTextureRect(Rect(0,3));
  45. // (注意 不同的控制器,可能在不同的层 其y值不同) 3 和1.5
  46. ground->setPosition(winSize.width/2,1.5+positionY);
  47. // 添加到Layer
  48. layer->addChild(ground);
  49. //**************************************
  50. // 3、添加Hero
  51. hero = Hero::create();
  52. // (注意 不同的控制器,可能在不同的层 其y值不同)
  53. hero->setPosition(50,hero->getContentSize().height/2+positionY);
  54. // 添加到Layer
  55. layer->addChild(hero);
  56. // 每添加一个新的障碍物之后,需重置 用于累计 记录 流逝的时间 的变量
  57. resetTempTimeDelta();
  58. return true;
  59. }
  60.  
  61. #pragma mark - 供外界场景调用
  62. // 供场景调用,让场景来 开启和关闭 游戏控制器 中的 时钟方法
  63. void GameCtrl::startUpdate(float dt)
  64. {
  65. // 临时变量,用于累计 记录 流逝的时间
  66. tempTimeDelta++;
  67. // 总共的时间间隔 (即 时间delta累计到 该间隔时,创建并添加一个障碍物)
  68. if (tempTimeDelta >= totalIntervalTime)
  69. {
  70. // 每添加一个新的障碍物之后,需重置 用于累计 记录 流逝的时间 的变量
  71. resetTempTimeDelta();
  72. // 每隔 随机的时间,创建并添加一个障碍物
  73. addBlock();
  74. }
  75. }
  76. // 每添加一个新的障碍物之后,需重置 用于累计 记录 流逝的时间 的变量
  77. void GameCtrl::resetTempTimeDelta()
  78. {
  79. tempTimeDelta = 0;
  80. totalIntervalTime = (rand()%120) + 100;
  81. }
  82.  
  83. // 创建 并 添加 障碍物 (在随机的 时间 间隔 之后 )
  84. void GameCtrl::addBlock()
  85. {
  86. auto b = Block::create();
  87. _layer->addChild(b);
  88. // 注意 障碍物的y值是 和当前游戏控制器 自己的y值 相同的
  89. // 即 block的半高 + 当前控制器自己的y
  90. b->setPositionY(b->getContentSize().height/2 + _positionY);
  91. }
  92.  
  93.  
  94. #pragma mark - 触摸事件
  95. // 当被用户触摸了 时侯调用,给英雄一个向上的速度
  96. void GameCtrl::onUserTouch()
  97. {
  98. hero->getPhysicsBody()->setVelocity(Vec2(0,400));
  99. }
  100.  
  101. bool GameCtrl::hitTestPoint(cocos2d::Vec2 point)
  102. {
  103. return boundary->getBoundingBox().containsPoint(point);
  104. }


边框、边界
  1. //
  2. // Boundary.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. // 边框、边界,其大小和winSize一样
  8.  
  9. #ifndef __Boundary__
  10. #define __Boundary__
  11.  
  12.  
  13.  
  14. #include <cocos2d.h>
  15.  
  16. USING_NS_CC;
  17.  
  18. class Boundary:public Node {
  19. public:
  20. // 宏定义 一个静态的create方法,内部会调用init方法
  21. CREATE_FUNC(Boundary);
  22. // 初始化方法
  23. virtual bool init();
  24. };
  25.  
  26. #endif /* defined(__Boundary__) */


  1. //
  2. // Boundary.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. // 边框、边界,其大小和winSize一样
  8.  
  9. #include "Boundary.h"
  10.  
  11.  
  12. bool Boundary::init(){
  13. // 父类的init方法,内部 直接返回一个true
  14. Node::init();
  15. // 960 * 640
  16. Size winSize = Director::getInstance()->getVisibleSize();
  17. // 设置Node大小 全屏
  18. setContentSize(winSize);
  19. // 设置物理刚体body,大小和winSize一样
  20. setPhysicsBody(PhysicsBody::createEdgeBox(winSize));
  21.  
  22. return true;
  23. }


Hero主角
  1. //
  2. // Hero.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. // 主角,继承自Sprite,奔跑的小人
  8.  
  9. #ifndef ___1_cocos2d_x__Hero__
  10. #define ___1_cocos2d_x__Hero__
  11.  
  12. #include <cocos2d.h>
  13.  
  14. USING_NS_CC;
  15.  
  16. class Hero:public Sprite {
  17. public:
  18. // 宏,静态的create方法,内部会调用init方法
  19. CREATE_FUNC(Hero);
  20. virtual bool init();
  21.  
  22. };
  23.  
  24.  
  25. #endif /* defined(___1_cocos2d_x__Hero__) */


  1. //
  2. // Hero.cpp
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. // 主角,奔跑的小人
  8.  
  9. #include "Hero.h"
  10.  
  11. #include "FlashTool.h"
  12.  
  13.  
  14. bool Hero::init()
  15. {
  16. // 父类的init方法
  17. Sprite::init();
  18. // 执行 帧动画 一直奔跑 RepeatForever
  19. runAction(RepeatForever::create(FlashTool::animateFromJsonFile("Hero.json",0.2f)));
  20.  
  21. // Json中的尺寸
  22. Size s = Size(44,52);
  23. // 精灵的大小
  24. setContentSize(s);
  25. // 设置物理世界的刚体body
  26. setPhysicsBody(PhysicsBody::createBox(s));
  27. // 刚体不允许 旋转
  28. getPhysicsBody()->setRotationEnable(false);
  29. // 重要~~~若想参与 碰撞,必须绑定一个碰撞标识
  30. getPhysicsBody()->setContactTestBitmask(1);
  31. return true;
  32. }


障碍物
  1. //
  2. // Block.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #ifndef ___1_cocos2d_x__Block__
  10. #define ___1_cocos2d_x__Block__
  11.  
  12. #include <cocos2d.h>
  13.  
  14. USING_NS_CC;
  15.  
  16. class Block:public Sprite {
  17. public:
  18. // 宏,内部会调用init方法
  19. CREATE_FUNC(Block);
  20. virtual bool init();
  21. // 时钟方法,内部会 让 障碍物不断地向左移动
  22. virtual void update(float dt);
  23.  
  24. };
  25.  
  26. #endif /* defined(___1_cocos2d_x__Block__) */


  1. //
  2. // Block.cpp
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #include "Block.h"
  10.  
  11. bool Block::init()
  12. {
  13. // 父类的init方法
  14. Sprite::init();
  15. // 屏幕大小
  16. Size winSize = Director::getInstance()->getVisibleSize();
  17. // 放在屏幕的外边
  18. setPositionX(winSize.width);
  19. // 黑色 障碍物
  20. setColor(Color3B(0,0));
  21.  
  22. Size size = Size((rand()%20)+5,(rand()%30)+10);
  23. // 随机生成 不同大小的 障碍物
  24. setContentSize(size);
  25. // 黑色的方块区域
  26. setTextureRect(Rect(0,size.width,size.height));
  27. // ***************************************
  28. // 设置 物理刚体
  29. setPhysicsBody(PhysicsBody::createBox(size));
  30. // 不是动态的刚体 即:是静态的刚体
  31. getPhysicsBody()->setDynamic(false);
  32. // 重要~~~若想参与 碰撞,必须绑定一个碰撞标识
  33. getPhysicsBody()->setContactTestBitmask(1);
  34. // ***************************************
  35. // 开启时钟方法
  36. scheduleUpdate();
  37. return true;
  38. }
  39. #pragma mark - 时钟方法
  40. // 时钟方法,内部会 让 障碍物不断地向左移动
  41. void Block::update(float dt){
  42. this->setPositionX(getPositionX()-8);
  43. // 移动到屏幕外边时,就停止消息调度,并且移除
  44. if (getPositionX()<0)
  45. {
  46. unscheduleUpdate();
  47. removeFromParent();
  48. }
  49. }


通过解析flash cc导出的Json文件+图片,

生成一个Animate对象,用于执行序列帧动画


  1. //
  2. // FlashTool.h
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #ifndef ___1_cocos2d_x__FlashTool__
  10. #define ___1_cocos2d_x__FlashTool__
  11.  
  12. #include <cocos2d.h>
  13.  
  14. USING_NS_CC;
  15.  
  16. class FlashTool {
  17. public:
  18. // 通过解析flash cc 导出的Json文件+大图片,生成一个Animate对象,用于执行序列帧动画
  19. static Animate * animateFromJsonFile(std::string jsonFile,float delayPerUnit);
  20. };
  21.  
  22. #endif /* defined(___1_cocos2d_x__FlashTool__) */


  1. //
  2. // FlashTool.cpp
  3. // 01_cocos2d-x
  4. //
  5. // Created by beyond on 14-10-6.
  6. //
  7. //
  8.  
  9. #include "FlashTool.h"
  10. // Json解析 使用cocos2d 内置的rapidJson库
  11. #include <json/document.h>
  12.  
  13. // 通过解析flash cc 导出的Json文件+大图片,用于执行序列帧动画
  14. Animate * FlashTool::animateFromJsonFile(std::string jsonFile,float delayPerUnit)
  15. {
  16. // 文档 对象
  17. rapidjson::Document doc;
  18. // FileUtils工具类 读入json文件
  19. std::string fileContent = FileUtils::getInstance()->getStringFromFile(jsonFile);
  20. //
  21. fileContent.erase(0,fileContent.find_first_of('{'));
  22. // 标记默认为 0,开始解析
  23. doc.Parse<0>(fileContent.c_str());
  24. // 得到大图片图片
  25. std::string imgFileName = doc["Meta"]["image"].GetString();
  26. auto &frames = doc["frames"];
  27. // 精灵帧缓存
  28. auto sfc = SpriteFrameCache::getInstance();
  29. // 容器用于 存放所有的 动画帧
  30. Vector<AnimationFrame*> animFrames;
  31. // 遍历,裁剪,创建,添加到容器
  32. for (auto m=frames.MemberonBegin(); m!=frames.MemberonEnd(); m++) {
  33. auto frameName = m->name.GetString();
  34. auto & frameProperties = m->value["frame"];
  35. auto & spriteSourceSize = m->value["spriteSourceSize"];
  36. auto sf = sfc->getSpriteFrameByName(frameName);
  37. if (!sf) {
  38. sf = SpriteFrame::create(imgFileName,Rect(frameProperties["x"].GetInt(),frameProperties["y"].GetInt(),frameProperties["w"].GetInt(),frameProperties["h"].GetInt()),m->value["rotated"].GetBool(),Vec2(spriteSourceSize["x"].GetInt(),spriteSourceSize["y"].GetInt()),Size(spriteSourceSize["w"].GetInt(),spriteSourceSize["h"].GetInt()));
  39. sfc->addSpriteFrame(sf,frameName);
  40. }
  41. animFrames.pushBack(AnimationFrame::create(sf,delayPerUnit,ValueMapNull));
  42. }
  43. // 生成用于Action的Animate
  44. Animation * animation = Animation::create(animFrames,delayPerUnit);
  45. return Animate::create(animation);
  46. }


flash cc 导出的Json文件+图片


  1. {"frames": {
  2.  
  3. "hero0000":
  4. {
  5. "frame": {"x":0,"y":0,"w":44,"h":52},"rotated": false,"trimmed": false,"spriteSourceSize": {"x":0,"sourceSize": {"w":44,"h":52}
  6. },"hero0001":
  7. {
  8. "frame": {"x":44,"w":42,"trimmed": true,"spriteSourceSize": {"x":2,"hero0002":
  9. {
  10. "frame": {"x":86,"hero0003":
  11. {
  12. "frame": {"x":0,"y":52,"hero0004":
  13. {
  14. "frame": {"x":42,"h":52}
  15. }},"Meta": {
  16. "app": "Adobe Flash Professional","version": "13.1.0.226","image": "Hero.png","format": "RGBA8888","size": {"w":128,"h":128},"scale": "1"
  17. }
  18. }

猜你在找的Cocos2d-x相关文章