初写Cocos2dX Box demo

前端之家收集整理的这篇文章主要介绍了初写Cocos2dX Box demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Appdelegate.h

  1. #ifndef _APP_DELEGATE_H_
  2. #define _APP_DELEGATE_H_
  3.  
  4. #include "cocos2d.h"
  5.  
  6. /**
  7. @brief The cocos2d Application.
  8.  
  9. Private inheritance here hides part of interface from Director.
  10. */
  11. class AppDelegate : private cocos2d::Application
  12. {
  13. public:
  14. AppDelegate();
  15. virtual ~AppDelegate();
  16.  
  17. virtual void initGLContextAttrs();
  18.  
  19. /**
  20. @brief Implement Director and Scene init code here.
  21. @return true Initialize success,app continue.
  22. @return false Initialize Failed,app terminate.
  23. */
  24. virtual bool applicationDidFinishLaunching();
  25.  
  26. /**
  27. @brief Called when the application moves to the background
  28. @param the pointer of the application
  29. */
  30. virtual void applicationDidEnterBackground();
  31.  
  32. /**
  33. @brief Called when the application reenters the foreground
  34. @param the pointer of the application
  35. */
  36. virtual void applicationWillEnterForeground();
  37. };
  38.  
  39. #endif // _APP_DELEGATE_H_

Appdelegate.m

  1. #include "AppDelegate.h"
  2. #include "HelloWorldScene.h"
  3.  
  4. USING_NS_CC;
  5.  
  6. static cocos2d::Size designResolutionSize = cocos2d::Size(480,320);
  7. static cocos2d::Size smallResolutionSize = cocos2d::Size(480,320);
  8. static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024,768);
  9. static cocos2d::Size largeResolutionSize = cocos2d::Size(2048,1536);
  10.  
  11. static cocos2d::Size iphoneSixResolutionSize = cocos2d::Size(1334,750);
  12.  
  13. AppDelegate::AppDelegate()
  14. {
  15. }
  16.  
  17. AppDelegate::~AppDelegate()
  18. {
  19. }
  20.  
  21. // if you want a different context,modify the value of glContextAttrs
  22. // it will affect all platforms
  23. void AppDelegate::initGLContextAttrs()
  24. {
  25. // set OpenGL context attributes: red,green,blue,alpha,depth,stencil
  26. GLContextAttrs glContextAttrs = {8,8,24,8};
  27.  
  28. GLView::setGLContextAttrs(glContextAttrs);
  29. }
  30.  
  31. // if you want to use the package manager to install more packages,// don't modify or remove this function
  32. static int register_all_packages()
  33. {
  34. return 0; //flag for packages manager
  35. }
  36.  
  37. bool AppDelegate::applicationDidFinishLaunching() {
  38. // initialize director
  39. auto director = Director::getInstance();
  40. auto glview = director->getOpenGLView();
  41. if(!glview) {
  42. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
  43. glview = GLViewImpl::createWithRect("TestBox2",cocos2d::Rect(0,designResolutionSize.width,designResolutionSize.height));
  44. #else
  45. glview = GLViewImpl::create("TestBox2");
  46. #endif
  47. director->setOpenGLView(glview);
  48. }
  49.  
  50. // turn on display FPS
  51. director->setDisplayStats(true);
  52.  
  53. // set FPS. the default value is 1.0/60 if you don't call this
  54. director->setAnimationInterval(1.0f / 60);
  55.  
  56. // Set the design resolution
  57. glview->setDesignResolutionSize(iphoneSixResolutionSize.width,iphoneSixResolutionSize.height,ResolutionPolicy::NO_BORDER);
  58. auto frameSize = glview->getFrameSize();
  59. // if the frame's height is larger than the height of medium size.
  60. if (frameSize.height > mediumResolutionSize.height)
  61. {
  62. director->setContentScaleFactor(MIN(largeResolutionSize.height/iphoneSixResolutionSize.height,largeResolutionSize.width/iphoneSixResolutionSize.width));
  63. }
  64. // if the frame's height is larger than the height of small size.
  65. else if (frameSize.height > smallResolutionSize.height)
  66. {
  67. director->setContentScaleFactor(MIN(mediumResolutionSize.height/iphoneSixResolutionSize.height,mediumResolutionSize.width/iphoneSixResolutionSize.width));
  68. }
  69. // if the frame's height is smaller than the height of medium size.
  70. else
  71. {
  72. director->setContentScaleFactor(MIN(smallResolutionSize.height/iphoneSixResolutionSize.height,smallResolutionSize.width/iphoneSixResolutionSize.width));
  73. }
  74.  
  75. register_all_packages();
  76.  
  77. // create a scene. it's an autorelease object
  78. auto scene = HelloWorld::createScene();
  79.  
  80. // run
  81. director->runWithScene(scene);
  82.  
  83. return true;
  84. }
  85.  
  86. // This function will be called when the app is inactive. Note,when receiving a phone call it is invoked.
  87. void AppDelegate::applicationDidEnterBackground() {
  88. Director::getInstance()->stopAnimation();
  89.  
  90. // if you use SimpleAudioEngine,it must be paused
  91. // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
  92. }
  93.  
  94. // this function will be called when the app is active again
  95. void AppDelegate::applicationWillEnterForeground() {
  96. Director::getInstance()->startAnimation();
  97.  
  98. // if you use SimpleAudioEngine,it must resume here
  99. // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
  100. }
HelloWorldScene.h
  1. #ifndef __HELLOWORLD_SCENE_H__
  2. #define __HELLOWORLD_SCENE_H__
  3.  
  4. #include "cocos2d.h"
  5. #include "external/Box2D/Box2D.h"
  6.  
  7. class HelloWorld : public cocos2d::Layer
  8. {
  9. protected:
  10. b2World *_world;
  11. cocos2d::Sprite *_ball;
  12. cocos2d::DrawNode *_graphics;
  13. cocos2d::Size _visibleSize;
  14. public:
  15. static cocos2d::Scene* createScene();
  16. virtual bool init();
  17. virtual void update(float delta);
  18. // a selector callback
  19. void menuCloseCallback(cocos2d::Ref* pSender);
  20. // implement the "static create()" method manually
  21. CREATE_FUNC(HelloWorld);
  22. //初始化球精灵
  23. void initBall(float xdt,float ydt,b2Vec2 aVec2);
  24. //初始化四周墙壁
  25. void initFence();
  26. //初始化地面
  27. void initGround();
  28. //初始化左右墙
  29. void initLeftRightWall();
  30. // 初始化天花板
  31. void initSky();
  32. // virtual void onTouchesBegan (const std::vector< cocos2d::Touch * > &touches,cocos2d::Event *unused_event);
  33.  
  34. // 触摸开始
  35. virtual bool onTouchBegan(cocos2d::Touch* touch,cocos2d::Event *event);
  36. //触摸结束
  37. virtual void onTouchEnded(cocos2d::Touch *touch,cocos2d::Event *unused_event);
  38. };
  39.  
  40. #endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
  1. #include "HelloWorldScene.h"
  2. #include "SimpleAudioEngine.h"
  3.  
  4. USING_NS_CC;
  5. #define RATIO 32
  6.  
  7. Scene* HelloWorld::createScene()
  8. {
  9. // 'scene' is an autorelease object
  10. auto scene = Scene::create();
  11. // 'layer' is an autorelease object
  12. auto layer = HelloWorld::create();
  13. // add layer as a child to scene
  14. scene->addChild(layer);
  15. // return the scene
  16. return scene;
  17. }
  18.  
  19. // on "init" you need to initialize your instance
  20. bool HelloWorld::init()
  21. {
  22. //////////////////////////////
  23. // 1. super init first
  24. if ( !Layer::init() )
  25. {
  26. return false;
  27. }
  28.  
  29. _world = new b2World(b2Vec2(0,-8));
  30. _visibleSize = Director::getInstance()->getVisibleSize();
  31.  
  32. //初始化四周墙壁
  33. initFence();
  34. // //初始化背景墙
  35. // initGround();
  36. // //初始化左右墙
  37. // initLeftRightWall();
  38. // //初始化天花板
  39. // initSky();
  40. //初始化球精灵1
  41. initBall(300,400,b2Vec2(2,0));
  42. //初始化球精灵2
  43. initBall(100,200,b2Vec2(4,0));
  44. //初始化球精灵3
  45. initBall(100,b2Vec2(1,0));
  46. //初始化球精灵4
  47. initBall(200,600,15));
  48. auto dispatcher = Director::getInstance()->getEventDispatcher();
  49. auto listener = EventListenerTouchOneByOne::create();
  50. listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
  51. listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved,this);
  52. listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded,this);
  53. listener->setSwallowTouches(true);//不向下传递触摸
  54. dispatcher->addEventListenerWithSceneGraPHPriority(listener,this);
  55. //即时更新
  56. scheduleUpdate();
  57. return true;
  58. }
  59.  
  60. void HelloWorld::initBall(float xdt,b2Vec2 aVec2)
  61. {
  62. Vec2 origin = Director::getInstance()->getVisibleOrigin();
  63. //创建显示对象,小球
  64. _ball = Sprite::create("smallBall.png");
  65. addChild(_ball);
  66. // _ball->setPosition(Vec2(200,200));
  67. // _ball->setAnchorPoint(Vec2(0,0));
  68. // _ball->setScale(1,1);
  69. //声明b2BodyDef
  70. b2BodyDef bodyDef;
  71. bodyDef.type= b2_dynamicBody;
  72. bodyDef.position.Set(xdt/RATIO,ydt/RATIO);
  73. //创建刚体所需的形状
  74. b2CircleShape circleShape;
  75. circleShape.m_radius = _ball->getContentSize().width/2/RATIO;
  76. //声明b2FixtureDef
  77. b2FixtureDef fixtureDef;
  78. fixtureDef.shape = &circleShape;
  79. fixtureDef.density= 10.0f;
  80. fixtureDef.friction= 1.8f;
  81. //创建刚体
  82. auto circle = _world->CreateBody(&bodyDef);
  83. circle->CreateFixture(&fixtureDef);
  84. circle->SetLinearVelocity(aVec2);
  85. // circle->ApplyLinearImpulse(b2Vec2(2,0),circle->GetLocalCenter(),true);
  86. circle->SetUserData(_ball);
  87. }
  88.  
  89. void HelloWorld::initFence()
  90. {
  91. //地板的位置和类型,(静态)
  92. b2BodyDef bodyDef;
  93. bodyDef.type = b2_staticBody;
  94. bodyDef.position = b2Vec2(0,0);
  95. b2Body *body = _world->CreateBody(&bodyDef);
  96. //指定形状,这一步骤必须有
  97. //下
  98. b2PolygonShape groundShape;
  99. groundShape.SetAsBox(_visibleSize.width/RATIO,0.1);//visibleSize.height/2.0/RATIO);
  100. b2FixtureDef fixture;
  101. // fixture.density = 1;//密度
  102. // fixture.friction = 0;//摩擦力
  103. // fixture.restitution = 0.8;
  104. fixture.shape = &groundShape;
  105. body->CreateFixture(&fixture);
  106. //上
  107. b2PolygonShape upShape;
  108. upShape.SetAsBox(_visibleSize.width/RATIO,0.1,b2Vec2(0,_visibleSize.height/RATIO),0);
  109. b2FixtureDef upFixture;
  110. upFixture.shape = &upShape;
  111. body->CreateFixture(&upFixture);
  112. //左
  113. b2PolygonShape leftShape;
  114. leftShape.SetAsBox(0.1,_visibleSize.height/RATIO,0);
  115. b2FixtureDef leftFixture;
  116. leftFixture.shape = &leftShape;
  117. body->CreateFixture(&leftFixture);
  118. //右
  119. b2PolygonShape rightShape;
  120. rightShape.SetAsBox(0.1,b2Vec2(_visibleSize.width/RATIO,0);
  121. b2FixtureDef rightFixture;
  122. rightFixture.shape = &rightShape;
  123. body->CreateFixture(&rightFixture);
  124. //设置地板,这里用的是精灵,图片可以自己设定,也可以用UI 进行绘图:
  125. Sprite *sp = Sprite::create("ground.png");
  126. sp->setAnchorPoint(Vec2(0,0));
  127. sp->setPosition(Vec2(0,100));
  128. sp->setScale(_visibleSize.width/(sp->getContentSize().width + 300),_visibleSize.height/sp->getContentSize().height);
  129. this->addChild(sp);
  130. body->SetUserData(sp);
  131.  
  132. }
  133.  
  134. void HelloWorld::initGround()
  135. {
  136. //地板的位置和类型,(静态)
  137. b2BodyDef bodyDef;
  138. bodyDef.type = b2_staticBody;
  139. bodyDef.position = b2Vec2(0,0);
  140. b2Body *body = _world->CreateBody(&bodyDef);
  141. //指定形状,这一步骤必须有
  142. b2PolygonShape groundShape;
  143. groundShape.SetAsBox(_visibleSize.width/RATIO,0.1);//visibleSize.height/2.0/RATIO);
  144. b2FixtureDef fixture;
  145. fixture.density = 1;//密度
  146. fixture.friction = 0;//摩擦力
  147. fixture.restitution = 0.8;
  148. fixture.shape = &groundShape;
  149. body->CreateFixture(&fixture);
  150. //设置地板,这里用的是精灵,图片可以自己设定,也可以用UI 进行绘图:
  151. Sprite *sp = Sprite::create("ground.png");
  152. sp->setAnchorPoint(Vec2(0,0));
  153. sp->setScale(_visibleSize.width/sp->getContentSize().width,_visibleSize.height/sp->getContentSize().height);
  154. this->addChild(sp);
  155. body->SetUserData(sp);
  156. }
  157.  
  158. void HelloWorld::initLeftRightWall()
  159. {
  160. //左墙===================================
  161. //地板的位置和类型,(静态)
  162. b2BodyDef bodyDef;
  163. bodyDef.type = b2_staticBody;
  164. bodyDef.position = b2Vec2(0,0);
  165. b2Body *body = _world->CreateBody(&bodyDef);
  166. //指定形状,这一步骤必须有
  167. b2PolygonShape groundShape;
  168. groundShape.SetAsBox(0.1,_visibleSize.height/RATIO);//visibleSize.height/2.0/RATIO);
  169. b2FixtureDef fixture;
  170. fixture.density = 1;//密度
  171. fixture.friction = 0.8;//摩擦力
  172. fixture.restitution = 0.8;
  173. fixture.shape = &groundShape;
  174. body->CreateFixture(&fixture);
  175. body->SetUserData(nullptr);
  176. //右墙===================================
  177. //地板的位置和类型,(静态)
  178. b2BodyDef bodyRightDef;
  179. bodyRightDef.type = b2_staticBody;
  180. bodyRightDef.position = b2Vec2(_visibleSize.width/RATIO,0);
  181. b2Body *bodyRight = _world->CreateBody(&bodyRightDef);
  182. //指定形状,这一步骤必须有
  183. b2PolygonShape groundRightShape;
  184. groundRightShape.SetAsBox(0.1,_visibleSize.height/RATIO);//visibleSize.height/2.0/RATIO);
  185. b2FixtureDef fixtureRight;
  186. fixtureRight.density = 1;//密度
  187. fixtureRight.friction = 0.8;//摩擦力
  188. fixtureRight.restitution = 0.8;
  189. fixtureRight.shape = &groundRightShape;
  190. bodyRight->CreateFixture(&fixtureRight);
  191. bodyRight->SetUserData(nullptr);
  192. }
  193.  
  194. void HelloWorld::initSky()
  195. {
  196. //地板的位置和类型,(静态)
  197. b2BodyDef bodyDef;
  198. bodyDef.type = b2_staticBody;
  199. bodyDef.position = b2Vec2(0,_visibleSize.height/RATIO);
  200. b2Body *body = _world->CreateBody(&bodyDef);
  201. //指定形状,这一步骤必须有
  202. b2PolygonShape groundShape;
  203. groundShape.SetAsBox(_visibleSize.width/RATIO,0.1);//visibleSize.height/2.0/RATIO);
  204. b2FixtureDef fixture;
  205. fixture.density = 1;//密度
  206. fixture.friction = 0.8;//摩擦力
  207. fixture.restitution = 0.8;
  208. fixture.shape = &groundShape;
  209. body->CreateFixture(&fixture);
  210. body->SetUserData(nullptr);
  211. }
  212.  
  213. void HelloWorld::update(float dt)
  214. {
  215. _world->Step(dt,10,10);
  216. Sprite * bird;
  217. for (b2Body *body = _world->GetBodyList(); body; body = body->GetNext())
  218. {
  219. if (body->GetType() == b2_dynamicBody)
  220. {
  221. bird = (Sprite*)body->GetUserData();
  222. bird->setPosition(Vec2(body->GetPosition().x*RATIO,body->GetPosition().y*RATIO));//设置动态物体的位置
  223. }
  224. else if (body->GetType() == b2_staticBody)
  225. {
  226.  
  227. }
  228. }
  229. }
  230.  
  231. //// 两种方式接受点击事件,一种
  232. //void HelloWorld::onTouchesBegan (const std::vector< Touch * > &touches,Event *unused_event)
  233. //{
  234. // CCLOG("touch this");
  235. //}
  236.  
  237. bool HelloWorld::onTouchBegan(Touch* touch,Event *event)
  238. {
  239. return true;
  240. }
  241.  
  242. void HelloWorld::onTouchEnded(cocos2d::Touch *touch,cocos2d::Event *unused_event)
  243. {
  244. CCLOG("touch is:%f---%f",touch->getLocation().x,touch->getLocation().y);
  245. //初始化球精灵1
  246. initBall(touch->getLocation().x,touch->getLocation().y,0));
  247. }
  248.  
  249. void HelloWorld::menuCloseCallback(Ref* pSender)
  250. {
  251. //Close the cocos2d-x game scene and quit the application
  252. Director::getInstance()->end();
  253. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  254. exit(0);
  255. #endif
  256. /*To navigate back to native iOS screen(if present) without quitting the application,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/
  257. //EventCustom customEndEvent("game_scene_close_event");
  258. //_eventDispatcher->dispatchEvent(&customEndEvent);
  259. }

ground.png



smallBall.png

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