Box2D:可以创建世界
世界:可以创建物体
物体:有【静止,运动,漂浮的】,物体可以与cocos2dx的各种元素绑定在一起,创建身躯后,可以实现各种机制,比如碰撞检测
另外:Box2D以米为单位,Cocos2dx以像素为单位,B转换成C时要乘上比例系数80
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#define RATIO 80.0f //转换比例
class HelloWorld : public cocos2d::Layer,public b2ContactListener
{
private:
b2World *world;
b2Body *floorBody;
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
//update对应世界一帧一帧执行
virtual void update(float dt);
virtual void BeginContact(b2Contact* contact);
void addRect(float posittionX, float positionY, b2BodyType type);
void addFloor();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
bool HelloWorld::init()
{
//
// 1. super init first
if ( !Layer::init() )
{
return false;
}
//指定世界加速的方向
world = new b2World(b2Vec2(0,-10));
//添加事件监听器
world->SetContactListener(this);
addFloor();
addRect(5,3,b2_dynamicBody);
//addRect(1,5,b2_kinematicBody); //漂浮的物体,不受重力影响而已,可以运动
scheduleUpdate();//启动update方法,逐帧执行update方法
return true;
}
//监听物体A和B
void HelloWorld::BeginContact(b2Contact* contact){
if(contact->GetFixtureA()->GetBody()==floorBody||contact->GetFixtureB()->GetBody()==floorBody){
CCLOG("Someting on the floor!");
}
}
void HelloWorld::addRect(float posittionX, float positionY, b2BodyType type){
//box2d,单位是米
b2BodyDef def;
def.position = b2Vec2(posittionX,positionY);
def.linearVelocity = b2Vec2(0,10); //指定初始线性速度
def.type = type;
b2Body* body = world->CreateBody(&def);
b2PolygonShape shape;
shape.SetAsBox(0.5,0.5);//默认指半宽和半高为中心,上下左右都是半
//创建该物体的身躯,使其可以与其它物体产生相互作用
b2FixtureDef fixDef;
fixDef.density = 1;//密度
fixDef.friction = 0.3;//摩擦系数
fixDef.shape = &shape;//指定图形区域
body->CreateFixture(&fixDef);
//cocos
auto s = Sprite::create();
s->setTextureRect(Rect(0,0,0.5*2*RATIO,0.5*2*RATIO)); //宽高要与body的身躯一致
addChild(s);
body->SetUserData(s);//将图形与Body绑定起来,将Sprite的值传给body
}
void HelloWorld::update(float dt){
//控制帧
world->Step(dt,8,3);
Sprite *s;
//获取所有子集物体
for (b2Body *b = world->GetBodyList(); b; b=b->GetNext()){
if (b->GetUserData()){
s = (Sprite*)b->GetUserData(); //如果检测到Body有值,则把值传给Sprite
s->setPosition(b->GetPosition().x*RATIO,b->GetPosition().y*RATIO);//重新设置Sprite,使物体与Body同步
}
}
}
void HelloWorld::addFloor(){
b2BodyDef def;
def.position = b2Vec2(0,0);
def.type = b2_staticBody;
floorBody = world->CreateBody(&def);
b2PolygonShape floorShape;
floorShape.SetAsBox(400/RATIO,0.5);
//创建物体的身躯,使其可以与其他物体产生相互作用
b2FixtureDef fixtureDef;
fixtureDef.density = 1; //密度
fixtureDef.friction = 0.3; //摩擦系数
fixtureDef.shape = &floorShape;//指定图形区域
floorBody->CreateFixture(&fixtureDef);
}
1.运动的物体
2.静止的物体
3.漂浮的物体(不受重力影响)
4.碰撞检测(信息输出到控制台)