您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx box2d例子

2013-12-24 15:21 351 查看
先右击解决方案中的libExtensions 选属性c/c++ 与处理器 预处理器定义 CC_ENABLE_CHIPMUNK_INTEGRATION=1更改为CC_ENABLE_BOX2D_INTEGRATION=1

包含头文件

#include "physics_nodes/CCPhysicsSprite.h"

#include "Box2D/Box2D.h"

USING_NS_CC_EXT;

声明变量

Texture2D* _spriteTexture; // weak ref

b2World* world;

enum {

kTagParentNode = 1,

};

#define PTM_RATIO 32

初始化图片

SpriteBatchNode* parentBar = SpriteBatchNode::create("bar.png", 50);

_spriteTexture = parentBar->getTexture();

addChild(parentBar, 0, kTagParentNode);

创建地球

void LoadingLayer::initPhysics()

{

b2Vec2 gravity;

gravity.Set(-30.0f, -20);

world = new b2World(gravity);

// Do we want to let bodies sleep?

world->SetAllowSleeping(true);

world->SetContinuousPhysics(true);

b2BodyDef groundBodyDef;

groundBodyDef.position.Set(0, 0); // bottom-left corner

b2Body* groundBody = world->CreateBody(&groundBodyDef);

b2EdgeShape groundBox;

groundBox.Set(b2Vec2(0/PTM_RATIO,80/PTM_RATIO), b2Vec2(900/PTM_RATIO,80/PTM_RATIO));

groundBody->CreateFixture(&groundBox,0);

groundBox.Set(b2Vec2(189/PTM_RATIO,0/PTM_RATIO), b2Vec2(189/PTM_RATIO,500/PTM_RATIO));

groundBody->CreateFixture(&groundBox,0);

}

添加物体

void LoadingLayer::addNewSpriteAtPosition(Point p)

{

CCLOG("Add sprite %0.2f x %02.f",p.x,p.y);

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(0.4, 0.4);

b2FixtureDef fixtureDef;

fixtureDef.shape = &dynamicBox;



fixtureDef.density = 1;

fixtureDef.friction = 0.1f;

body->CreateFixture(&fixtureDef);



auto parent = this->getChildByTag(kTagParentNode);

PhysicsSprite* sprite = PhysicsSprite::createWithTexture(_spriteTexture,Rect(0,0,32*2,32*2));

parent->addChild(sprite);

sprite->setB2Body(body);

sprite->setPTMRatio(PTM_RATIO);

sprite->setPosition( Point( p.x, p.y) );

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: