建立工程Box2DTest,去掉背景和精靈對象等。首先在HelloWorldScene.h頭文件定義一個屏幕像素與物理世界長度轉換宏,並引入box2D頭文件框架
#define PIXEL_TO_METER 30 #include "Box2D/Box2D.h"
再聲明幾個函數與變量函數
void createWorld(); //建立物理世界 void createWall(); //建立四周牆體 void createBall(); //建立剛體
b2World* world;
b2Body* wallBody ;this
float32 wallLineOffset ;spa
createWorld實現rest
void HelloWorld::createWorld() { b2Vec2 gravity; gravity.Set(0.0f,-9.0f); //物理世界重力向量,這裏建立一個向下的重力向量 b2BodyDef* bodydef = new b2BodyDef(); world = new b2World(gravity); //根據重力向量建立物理世界對象 world->SetAllowSleeping(true); //容許休眠 world->SetWarmStarting(true); //初始狀態將受到重力影響 }
createWall實現code
void HelloWorld::createWall(){ CCSize s = CCDirector::sharedDirector()->getVisibleSize(); b2BodyDef wallDef ; //剛體定義 wallDef.position.Set(0,0); //位置 wallBody = world->CreateBody(&wallDef); //建立一個剛體(四周牆體) b2EdgeShape wallShape; //形狀 //下 wallLineOffset 方便調整顯示位置 wallShape.Set(b2Vec2(0,0+wallLineOffset), b2Vec2(s.width/PIXEL_TO_METER,0+wallLineOffset)); //設置形狀大小 wallBody->CreateFixture(&wallShape,0); //將形狀鏈接到框架上 //上 wallShape.Set(b2Vec2(0,s.height/PIXEL_TO_METER-wallLineOffset),b2Vec2(s.width/PIXEL_TO_METER,s.height/PIXEL_TO_METER-wallLineOffset)); wallBody->CreateFixture(&wallShape,0); //左 wallShape.Set(b2Vec2(0+wallLineOffset,s.height/PIXEL_TO_METER),b2Vec2(0+wallLineOffset,0)); wallBody->CreateFixture(&wallShape,0); //右 wallShape.Set(b2Vec2(s.width/PIXEL_TO_METER-wallLineOffset,s.height/PIXEL_TO_METER),b2Vec2(s.width/PIXEL_TO_METER-wallLineOffset,0)); wallBody->CreateFixture(&wallShape,0); }
createBall實現對象
void HelloWorld::createBall(){ CCSize s = CCDirector::sharedDirector()->getVisibleSize(); for(int i= 0; i < 5; i++) { b2BodyDef ballDef ; ballDef.type = b2_dynamicBody; //設置剛體爲動態物體 b2CircleShape circleShape ; //剛體碰撞使用的形狀 b2FixtureDef ballFixtureDef ; circleShape.m_p.Set(1.0+i,5.0); circleShape.m_radius= 0.5f; //剛體鏈接的框架設置 ballFixtureDef.shape = &circleShape; ballFixtureDef.density = 1.0; ballFixtureDef.restitution = 0.8; //設置重力恢復係數 ballFixtureDef.friction = 0.3f; ballDef.position.Set(s.width/2/PIXEL_TO_METER,20/PIXEL_TO_METER); b2Body* ball = world->CreateBody(&ballDef); //根據剛體定義建立剛體 ball->CreateFixture(&ballFixtureDef); //關聯框架到剛體上 } }
最後再init方法中添加以下代碼blog
wallLineOffset = 0.5; this->createWorld(); this->createWall(); this->createBall();
最後咱們運行看看什麼狀況ci
呵呵,咱們建立的物體世界沒有顯示出來,下一篇中咱們把物理世界顯示出來。get