cocos2dx box2d例子

先右击解决方案中的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) );


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值