【麥可網】Cocos2d-X跨平臺遊戲開發---學習筆記
第二十四課:Cocos2D-X物理引擎之Box2D1-7
=======================================================================================================================================================================
課程目標:
- 學習Box2D
課程重點:
- BOX2D概念
- BOX2D常用操作
- 使用物理編輯器
考覈目標:
- 能夠使用Box2D常用操作
- 使用物理編輯器完成物理對象編輯
=======================================================================================================================================================================
一、啓動BOX2D
1、選中你編譯的工程,按Alt + Enter快捷鍵(或者右鍵,選Propreties),在彈出的菜單中選擇C/C++ --> Preprocossor,將Preprocessor Definition下的CC_ENABLE_CHIPMUNK_INTEGRATION=1修改爲CC_ENABLE_BOX2D_INTEGRATION=1。
2、查看Linker -->Input下的Aditional Dependencies裏,有沒有libBox2d.lib。如果沒有,手動添加之。
3、libExtensions類庫也對應修改1和2步驟
二、實例一:使用BOX2D
HelloBox2D.h
--------------------
#pragma once
#include "cocos2d.h"
#include "Box2D/Box2D.h"
USING_NS_CC;
class HelloBox2D : public cocos2d::CCLayer
{
private:
CCTexture2D* m_pSpriteTexture;
b2World* world;
public:
HelloBox2D();
~HelloBox2D();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually
CREATE_FUNC(HelloBox2D);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
void initPhysics();
void addNewSpriteAtPosition(CCPoint p);
void updata(float dt);
};
HelloBox2D.cpp
--------------------
#include "HelloBox2D.h"
#include "cocos-ext.h"
using namespace cocos2d::extension;
USING_NS_CC;
enum{
kTagParentNode = 1,
};
#define PTM_RATIO 32.0f
CCScene* HelloBox2D::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloBox2D *layer = HelloBox2D::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
HelloBox2D::HelloBox2D():
m_pSpriteTexture(NULL),
world(NULL)
{
}
HelloBox2D::~HelloBox2D()
{
CC_SAFE_DELETE(world);
}
// on "init" you need to initialize your instance
bool HelloBox2D::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
setTouchEnabled(true);
setAccelerometerEnabled(true);
this->initPhysics();
CCSpriteBatchNode* blocks = CCSpriteBatchNode::create("blocks.png",100);
m_pSpriteTexture = blocks->getTexture();
addChild(blocks, 0, kTagParentNode);
//scheduleUpdate();
this->schedule(schedule_selector(HelloBox2D::updata));
return true;
}
void HelloBox2D::menuCloseCallback(CCObject* pSender)
{
}
void HelloBox2D::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
CCSetIterator it;
CCTouch* touch;
for (it=pTouches->begin(); it!=pTouches->end();it++)
{
touch = (CCTouch*)(*it);
if (!touch) break;
CCPoint location = touch->getLocation();
addNewSpriteAtPosition( location );
}
}
void HelloBox2D::initPhysics()
{
b2Vec2 gravity;
gravity.Set(0.0f,-10.0f);
world = new b2World(gravity);
world->SetAllowSleeping(true);
world->SetContinuousPhysics(true);
//創建物理空間的範圍
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0);
//創建剛體
b2Body* groundBody = world->CreateBody(&groundBodyDef);
//創建形狀
b2EdgeShape groundBox;
//創建夾具
//將形狀綁定到剛體上
//button
groundBox.Set(b2Vec2(0,0), b2Vec2(480/PTM_RATIO, 0));
groundBody->CreateFixture(&groundBox, 0);
//top
groundBox.Set(b2Vec2(0,320/PTM_RATIO), b2Vec2(480/PTM_RATIO, 320/PTM_RATIO));
groundBody->CreateFixture(&groundBox, 0);
//left
groundBox.Set(b2Vec2(0,320/PTM_RATIO), b2Vec2(0, 0));
groundBody->CreateFixture(&groundBox, 0);
//right
groundBox.Set(b2Vec2(480/PTM_RATIO,320/PTM_RATIO), b2Vec2(480/PTM_RATIO, 0));
groundBody->CreateFixture(&groundBox, 0);
}
void HelloBox2D::addNewSpriteAtPosition(CCPoint p)
{
//定義剛體
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);
//定義多邊形
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);
//定義夾具
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox; //形狀
fixtureDef.density = 1.0f; //密度
fixtureDef.friction = 0.3f; //摩擦係數
body->CreateFixture(&fixtureDef);
CCNode* parent = this->getChildByTag(kTagParentNode);
int idx = (CCRANDOM_0_1() < 0.5 ? 0 : 1);
int idy = (CCRANDOM_0_1() < 0.5 ? 0 : 1);
if (idx==0 && idy==0)
{
int a =100;
body->SetUserData(&a);
}
CCPhysicsSprite* sprite = CCPhysicsSprite::createWithTexture(m_pSpriteTexture, CCRectMake(32*idx, 32*idy, 32, 32));
parent->addChild(sprite);
sprite->setB2Body(body);
sprite->setPTMRatio(PTM_RATIO);
//sprite->setPosition( ccp( p.x, p.y) );//添加上這句在快速創建物理精靈時會出錯
}
void HelloBox2D::updata(float dt)
{
int velocityIterations = 8;
int positionIterations = 1;
world->Step(dt, velocityIterations, positionIterations);
#if 0
//遍歷剛體
for (b2Body* b=world->GetBodyList(); b; b=b->GetNext())
{
int* tmp = (int*)b->GetUserData();
if (*tmp == 100)
{
//千萬不要在這裏直接刪除b指向的body對象,緩存後在後面刪除
CCLOG("body is a");
}
}
//遍歷碰撞點
for ( b2Contact* c=world->GetContactList(); c; c=c->GetNext() )
{
////千萬不要在這裏直接刪除c指向的碰撞點對象,緩存後在後面刪除
}
#endif
}
<strong>碰撞前後的狀態</strong>
===================================================================
總結:
玩轉物理引擎,直達憤怒小鳥。
開心一刻:
4歲的男孩親3歲的女孩,
女孩很認真的問:“你親了我會對我負責嗎?”
男孩拍拍女孩的肩膀:“你放心,我們已不是一、兩歲的孩子了。”
【麥可網】Cocos2d-X跨平臺遊戲開發---教程下載:http://pan.baidu.com/s/1kTio1Av
【麥可網】Cocos2d-X跨平臺遊戲開發---筆記系列:http://blog.csdn.net/qiulanzhu