在Cocos2d-x3.0里面如何使用物理引擎:弹球

前端之家收集整理的这篇文章主要介绍了在Cocos2d-x3.0里面如何使用物理引擎:弹球前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

HelloWorldScene.h

  1. #ifndef __HELLOWORLD_SCENE_H__
  2. #define __HELLOWORLD_SCENE_H__
  3.  
  4. #include "cocos2d.h"
  5.  
  6. USING_NS_CC;
  7.  
  8. class HelloWorld : public cocos2d::Layer
  9. {
  10. public:
  11. // there's no 'id' in cpp,so we recommend returning the class instance pointer
  12. static cocos2d::Scene* createScene();
  13.  
  14. // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
  15. virtual bool init();
  16.  
  17. // a selector callback
  18. void menuCloseCallback(Object* pSender);
  19.  
  20. // implement the "static create()" method manually
  21. CREATE_FUNC(HelloWorld);
  22.  
  23. void setPhyWorld(PhysicsWorld* world){m_world = world;}
  24.  
  25. virtual bool onTouchBegan(Touch *touch,Event *unused_event);
  26. virtual void onTouchEnded(Touch *touch,Event *unused_event);
  27.  
  28. void addNewSpriteAtPosition(Point p);
  29.  
  30. private:
  31. PhysicsWorld* m_world;
  32.  
  33. //bool onContactBegin(EventCustom* event,const PhysicsContact& contact);
  34.  
  35. bool onContactBegin(PhysicsContact& contact);
  36. };
  37.  
  38. #endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp
  1. #include "HelloWorldScene.h"
  2.  
  3. USING_NS_CC;
  4.  
  5. Scene* HelloWorld::createScene()
  6. {
  7. // 'scene' is an autorelease object
  8. //add physicals
  9. auto scene = Scene::createWithPhysics();
  10. //DrawMask参数可以选择打开绘制哪些部分比如,Joint、Shape、Contact等等
  11. scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
  12.  
  13. //创建一个边界
  14. Size visibleSize = Director::getInstance()->getVisibleSize();
  15. //使用PhysicalsBody的create方法创建自己想要的物体。
  16. //PHYSICSBODY_MATERIAL_DEFAULT宏表示的是创建的Body的默认材质,3是边线宽度。编译运行我们会看到场景边上有红色的边界。
  17. auto body = PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT,3);
  18. auto edgeNode = Node::create();
  19. edgeNode->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
  20. edgeNode->setPhysicsBody(body);
  21. scene->addChild(edgeNode);
  22.  
  23. // 'layer' is an autorelease object
  24. auto layer = HelloWorld::create();
  25. //将这个World传到Layer中。所以我们在HelloWorld类中加入一个函数。将这个world存起来。
  26. layer->setPhyWorld(scene->getPhysicsWorld());
  27.  
  28. // add layer as a child to scene
  29. scene->addChild(layer);
  30.  
  31. // return the scene
  32. return scene;
  33. }
  34.  
  35. // on "init" you need to initialize your instance
  36. bool HelloWorld::init()
  37. {
  38. //////////////////////////////
  39. // 1. super init first
  40. if ( !Layer::init() )
  41. {
  42. return false;
  43. }
  44.  
  45. Size visibleSize = Director::getInstance()->getVisibleSize();
  46. Point origin = Director::getInstance()->getVisibleOrigin();
  47.  
  48. /////////////////////////////
  49. // 2. add a menu item with "X" image,which is clicked to quit the program
  50. // you may modify it.
  51.  
  52. // add a "close" icon to exit the progress. it's an autorelease object
  53. auto closeItem = MenuItemImage::create(
  54. "CloseNormal.png","CloseSelected.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback,this));
  55.  
  56. closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2,origin.y + closeItem->getContentSize().height/2));
  57.  
  58. // create menu,it's an autorelease object
  59. auto menu = Menu::create(closeItem,NULL);
  60. menu->setPosition(Point::ZERO);
  61. this->addChild(menu,1);
  62.  
  63. /////////////////////////////
  64. // 3. add your codes below...
  65.  
  66. // add a label shows "Hello World"
  67. // create and initialize a label
  68.  
  69. auto label = LabelTTF::create("Hello World","Arial",24);
  70.  
  71. // position the label on the center of the screen
  72. label->setPosition(Point(origin.x + visibleSize.width/2,origin.y + visibleSize.height - label->getContentSize().height));
  73.  
  74. // add the label as a child to this layer
  75. this->addChild(label,1);
  76.  
  77. // new way to enable touch
  78. auto touchListener = EventListenerTouchOneByOne::create();
  79. touchListener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
  80. touchListener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded,this);
  81. _eventDispatcher->addEventListenerWithSceneGraPHPriority(touchListener,this);
  82.  
  83. // 碰撞检测回调
  84. auto contactListener = EventListenerPhysicsContact::create();
  85. contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin,this);
  86. _eventDispatcher->addEventListenerWithSceneGraPHPriority(contactListener,this);
  87. return true;
  88. }
  89.  
  90. bool HelloWorld::onContactBegin(PhysicsContact& contact)
  91. {
  92. auto sp = (Sprite*)contact.getShapeA()->getBody()->getNode();
  93. int tag = sp->getTag();
  94. CCLOG("onContactBegin: %d",tag);
  95. return true;
  96. }
  97.  
  98. bool HelloWorld::onTouchBegan(Touch *touch,Event *unused_event)
  99. {
  100. return true;
  101. }
  102.  
  103. void HelloWorld::onTouchEnded(Touch *touch,Event *unused_event)
  104. {
  105. auto location = touch->getLocation();
  106. addNewSpriteAtPosition(location);
  107. }
  108.  
  109. //然后我们来实现addNewSpriteAtPosition函数
  110. //关联body与sprite从未如此简单,我们只需创建一个body,创建一个sprite然后将body设置为sprite的body即可。
  111. void HelloWorld::addNewSpriteAtPosition(Point p)
  112. {
  113. auto sprite = Sprite::create("ball.png");
  114. sprite->setTag(1);
  115. auto body = PhysicsBody::createCircle(sprite->getContentSize().width / 2);
  116. sprite->setPhysicsBody(body);
  117. sprite->setPosition(p);
  118. this->addChild(sprite);
  119. }
  120.  
  121. void HelloWorld::menuCloseCallback(Object* pSender)
  122. {
  123. //控制PhysicsWorld debugDraw的绘制
  124. if(m_world->getDebugDrawMask() != PhysicsWorld::DEBUGDRAW_NONE) {
  125. m_world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_NONE);
  126. } else {
  127. m_world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
  128. }
  129. }

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. The reason for implement as private inheritance is to hide some interface call by Director.
  10. */
  11. class AppDelegate : private cocos2d::Application
  12. {
  13. public:
  14. AppDelegate();
  15. virtual ~AppDelegate();
  16.  
  17. /**
  18. @brief Implement Director and Scene init code here.
  19. @return true Initialize success,app continue.
  20. @return false Initialize Failed,app terminate.
  21. */
  22. virtual bool applicationDidFinishLaunching();
  23.  
  24. /**
  25. @brief The function be called when the application enter background
  26. @param the pointer of the application
  27. */
  28. virtual void applicationDidEnterBackground();
  29.  
  30. /**
  31. @brief The function be called when the application enter foreground
  32. @param the pointer of the application
  33. */
  34. virtual void applicationWillEnterForeground();
  35. };
  36.  
  37. #endif // _APP_DELEGATE_H_

AppDelegate.cpp
  1. #include "AppDelegate.h"
  2. #include "HelloWorldScene.h"
  3.  
  4. USING_NS_CC;
  5.  
  6. AppDelegate::AppDelegate() {
  7.  
  8. }
  9.  
  10. AppDelegate::~AppDelegate()
  11. {
  12. }
  13.  
  14. bool AppDelegate::applicationDidFinishLaunching() {
  15. // initialize director
  16. // initialize director
  17. auto director = Director::getInstance();
  18. auto glview = director->getOpenGLView();
  19. if(!glview) {
  20. glview = GLViewImpl::create("My Game");
  21. director->setOpenGLView(glview);
  22. }
  23. // turn on display FPS
  24. director->setDisplayStats(true);
  25.  
  26. // set FPS. the default value is 1.0/60 if you don't call this
  27. director->setAnimationInterval(1.0 / 60);
  28.  
  29. glview->setDesignResolutionSize(800,600,ResolutionPolicy::EXACT_FIT);
  30.  
  31. // create a scene. it's an autorelease object
  32. auto scene = HelloWorld::createScene();
  33.  
  34. // run
  35. director->runWithScene(scene);
  36.  
  37. return true;
  38. }
  39.  
  40. // This function will be called when the app is inactive. When comes a phone call,it's be invoked too
  41. void AppDelegate::applicationDidEnterBackground() {
  42. Director::getInstance()->stopAnimation();
  43.  
  44. // if you use SimpleAudioEngine,it must be pause
  45. // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
  46. }
  47.  
  48. // this function will be called when the app is active again
  49. void AppDelegate::applicationWillEnterForeground() {
  50. Director::getInstance()->startAnimation();
  51.  
  52. // if you use SimpleAudioEngine,it must resume here
  53. // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
  54. }


用到的图片

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