Cocos2d Box2d 物理引擎实现愤怒的小鸟
这里我们修改HelloWorldScene场景,在这里实现
我们的思路是首先初始化一些刚体,,然后实现点击屏幕产生小鸟,松开小鸟,小鸟飞出,撞击初始化好的那些刚体,产生碰撞检测效果。
1.在HelloWorld.h中
#include"cocos2d.h"
#include"box2d/box2d.h"
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
{
public:
// there'sno 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here'sa difference. Method 'init' in cocos2d-x returns bool, instead of returning'id' in cocos2d-iphone
virtual bool init();
// aselector callback
void menuCloseCallback(cocos2d::Ref* pSender);
//implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
b2World*world;//创建一个物理世界
virtual bool onTouchBegan(Touch *touch, Event *unused_event);
virtual void onTouchMoved(Touch *touch, Event *unused_event);
virtual void onTouchEnded(Touch *touch, Event *unused_event);
void addNewPigAtPoint(int x,int y);
int pigIndex;//记录猪的编号
void update(float t);//
void initpig();//初始化一些猪
int birdIndex;//鸟德编号
void pigSmile(Sprite*spig,float x,float y,floatang);//猪笑了
void pigCry(Sprite*spig,float x,float y,floatang);//猪哭了
void birdContact(Sprite*spbird,float x ,float y,float ang);//鸟掉毛
};
#endif
2.在Helloworld.cpp中
#include"HelloWorldScene.h"
#include"box2d/box2d.h"
#include"BirdContact.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene'is an autorelease object
auto scene = Scene::create();
// 'layer'is an autorelease object
auto layer = HelloWorld::create();
// addlayer as a child to scene
scene->addChild(layer);
// returnthe scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//
// 1.super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto bg=Sprite::create("startbg.png");
this->addChild(bg);
bg->setPosition(Director::getInstance()->getWinSize().width/2,
Director::getInstance()->getWinSize().height/2);
//创建一个物理世界
b2Vec2 gravite;
gravite.Set(0.0f, -9.8f);//定义一个初始化的坐标--牛顿的重力
this->world=new b2World(gravite);//这个参数作为这个物理世界的特性
//定义物理世界的侦听----碰撞检测
BirdContact*listenerb=new BirdContact();//
world->SetContactListener(listenerb);//侦听和物理世界相互绑定
//创建一个静态的刚体--地板
b2BodyDef grounddef;
grounddef.position.Set(0.0f,120/32.0f);
b2Body*ground=world->CreateBody(&grounddef);
//创建家具定义刚体的形状
b2PolygonShape groundshape;//定义刚体的形状--为多边形
groundshape.SetAsBox(visibleSize.width/32, 10/32);//