需要引入的头文件
#include "cocos2d.h"
#include "Box2D\Box2D.h"
#include <string>
创建物理世界
world = new b2World(b2Vec2(0,-10));
创建会自由掉落的 精灵
bird = Sprite::create("bird0_0.png"); bird->setName("bird"); Size size = bird->getContentSize(); b2BodyDef def; def.type = b2_dynamicBody; def.position = b2Vec2(screenSize.width / 4 / RATIO,screenSize.height / 2 / RATIO + 1);//鸟的位置 b2PolygonShape shape; shape.SetAsBox(size.width/2/RATIO,size.height/2/RATIO); //碰撞体积? b2FixtureDef fixtureDef; fixtureDef.density = 1; fixtureDef.friction = 0.3; fixtureDef.shape = &shape; b2Body *body = world->CreateBody(&def); body->CreateFixture(&fixtureDef); addChild(bird); bird->setPosition(Point(def.position.x*RATIO,def.position.y*RATIO));//物理物体会自动往下掉 因此绑定物理物体的位置到sprite上 就形成了物理 body->SetUserData(bird);//与sprite绑定 this->body = body;
void HelloWorld::bingSprite(){ //让物理盒子和精灵实时绑定来达到物理效果 物理盒子本身是看不到的 Sprite *s; for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()){ s = (Sprite*)b->GetUserData(); if (b->GetUserData() && b->GetType() == b2_dynamicBody||b->GetType()==b2_kinematicBody){ if (s != NULL){ s->setPosition(b->GetPosition().x*RATIO,b->GetPosition().y*RATIO);//每次渲染都让sprite与Box body保持位置绑定 } } } }
Sprite *ground = Sprite::create("land.png"); Size size = ground->getContentSize(); ground->setScaleX(2); ground->setScaleY(2); b2BodyDef bDef; bDef.type = b2_staticBody; bDef.position = b2Vec2(size.width/2/RATIO,size.height/2/RATIO);//设置碰撞物体的位置 b2PolygonShape groundShape; groundShape.SetAsBox(size.width/2/RATIO,size.height/2/RATIO-0.3);//position 和SetAsBox 都可以改变碰撞物体的位置 不知为何 b2Body *groundBody = world->CreateBody(&bDef); b2FixtureDef fix; fix.shape = &groundShape; groundBody->CreateFixture(&fix); groundBody->SetUserData(ground); addChild(ground);
linearVelocity 是设置盒子执行的动作 如 往各个方向移动
物理盒子有 三种类型 漂浮物体 静态物体 和动态物体
漂浮物体不受重力音响 可自由移动,静态物体位置是固定的不会掉落, 动态物体会自由掉落
笔记至此结束
原文链接:https://www.f2er.com/cocos2dx/342109.html