cocos2d-x 3.10 显示Box2d 调试视图
1.将cocos2d-x-3.10\tests\cpp-tests\Classes\Box2DTestBed目录下的GLES-Render.h和GLES-Render.cpp拷贝到当前项目的Classes目录下。
2.在visual studio2013打开当前项目解决方案,在解决方案资源管理器的src下右键->添加->现有项,选择刚才拷贝到Classes目录下GLES-Render.h和GLES-Render.cpp。
Box2dTest.h
1 #ifndef _BOX2D_TEST_H_ 2 #define _BOX2D_TEST_H_ 3 #include "cocos2d.h" 4 #include "Box2D\Box2D.h" 5 USING_NS_CC; 6 class Box2dTest:public Node{ 7 public: 8 Box2dTest(); 9 ~Box2dTest(); 10 virtual bool init(); 11 void update(float) override; 12 virtual void draw(Renderer *renderer, const Mat4& transform, uint32_t flags) override; 13 CREATE_FUNC(Box2dTest); 14 private: 15 b2World* _world; 16 }; 17 #endif
Box2dTest.cpp
1 #include "Box2dTest.h" 2 #include "GLES-Render.h" 3 4 #define PTM_RATIO 32 5 6 Box2dTest::Box2dTest(){ 7 8 } 9 10 Box2dTest::~Box2dTest(){ 11 CC_SAFE_DELETE(_world); 12 } 13 14 bool Box2dTest::init(){ 15 if (!Node::init())return false; 16 _world = new b2World(b2Vec2(0.0f, 0.0f)); 17 18 //创建一个矩形刚体 19 b2BodyDef boxDef; 20 boxDef.position.Set(500/PTM_RATIO,350/PTM_RATIO); 21 b2Body* box = _world->CreateBody(&boxDef); 22 b2PolygonShape boxShape; 23 boxShape.SetAsBox(40/PTM_RATIO, 40/PTM_RATIO); 24 box->CreateFixture(&boxShape,1); 25 26 //调试视图 27 GLESDebugDraw* debugDraw = new GLESDebugDraw(PTM_RATIO); 28 _world->SetDebugDraw(debugDraw); 29 uint32 flags = 0; 30 flags += b2Draw::e_shapeBit; 31 flags += b2Draw::e_pairBit; 32 flags += b2Draw::e_centerOfMassBit; 33 debugDraw->SetFlags(flags); 34 35 scheduleUpdate(); 36 return true; 37 } 38 39 void Box2dTest::update(float delta){ 40 _world->Step(30.0f, 10, 10); 41 } 42 43 void Box2dTest::draw(Renderer *renderer, const Mat4& transform, uint32_t flags){ 44 Node::draw(renderer, transform, flags); 45 46 ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position); 47 kmGLPushMatrix(); 48 _world->DrawDebugData(); 49 kmGLPopMatrix(); 50 CHECK_GL_ERROR_DEBUG(); 51 }
HelloWorld.cpp下的init()函数下添加:
1 Box2dTest* box2dTest=Box2dTest::create(); 2 addChild(box2dTest);