//
// Box2dTest.cpp
// HelloCpp
//
// Created by 0卜7r从l on 13-12-7.
//
//
#include "Box2dTest.h"
#include "SpriteBox.h"
Scene *Box2dTest::createScene(){
Scene *scene=Scene::create();
Box2dTest *box2d=Box2dTest::create();
scene->addChild(box2d);
return scene;
}
bool Box2dTest::init(){
if (!Layer::init()) {
return false;
}
this->setTouchEnabled(true);
this->setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
//创建世界
b2Vec2 gravity;
//设置地心力
gravity.Set(0.0f, -10.0f);
//创建世界,
world=new b2World(gravity);
// this->createSp(Point(940/2, 600));
//
//
//创建地面
this->createBody();
// //debug显示世界
GLESDebugDraw *debugDraw = new GLESDebugDraw(PTM_RATIO);
debugDraw->SetFlags(b2Draw::e_shapeBit);
world->SetDebugDraw(debugDraw);
//定时器去执行物理世界动画
schedule(schedule_selector(Box2dTest::scheduleBox));
SpriteBox *box=SpriteBox::Create(world, "Icon-72.png",Point(900, 500),1);
this->addChild(box);
//设置摩擦力
box->getFixture()->SetFriction(1);
//弹性
box->getFixture()->SetRestitution(0.5);
return true;
}
void Box2dTest::scheduleBox(float t){
world->Step(t, 8, 1);
for (b2Body *body=world->GetBodyList();body!=NULL;body=body->GetNext()) {
Sprite *sprite=(Sprite*)body->GetUserData();
if (sprite!=NULL) {
Point point=Point(body->GetPosition().x*PTM_RATIO, body->GetPosition().y*PTM_RATIO);
sprite->setPosition(point);
sprite->setRotation(-1*CC_RADIANS_TO_DEGREES(body->GetAngle()));
}
}
}
#pragma mark 创建一个精灵
void Box2dTest::createSp(Point p){
sp=Sprite::create("Icon-72.png");
sp->setPosition(p);
this->addChild(sp);
//定义一个缸体
b2BodyDef bodyDef;
bodyDef.position.Set(10, 10);
bodyDef.type = b2_dynamicBody;
//通过世界创建一个刚体
b2Body *body=world->CreateBody(&bodyDef);
//定义一个形状
b2PolygonShape ground;
ground.SetAsBox(sp->getContentSize().width/PTM_RATIO/2, sp->getContentSize().height/PTM_RATIO/2);
//夹具,把形状放在刚体上
body->CreateFixture(&ground,10);
body->SetUserData(sp);
sp->setUserData(body);
}
#pragma mark 创建一个刚体
void Box2dTest::createBody(){
Size winSize=Director::getInstance()->getWinSize();
//创建一个平地
b2BodyDef bodyDef;
bodyDef.position.Set(10, 2);
// bodyDef.type = b2_dynamicBody;
//通过世界创建一个刚体
b2Body *body=world->CreateBody(&bodyDef);
//定义一个形状
b2PolygonShape ground;
ground.SetAsBox(10,0.5,b2Vec2(0, 0),CC_DEGREES_TO_RADIANS(10));
//夹具,把形状放在刚体上
body->CreateFixture(&ground,0);
}
//点击屏幕事件
bool Box2dTest::onTouchBegan(Touch *touch, Event *event){
SpriteBox *box=SpriteBox::Create(world, "Icon-72.png",touch->getLocation(),1000);
this->addChild(box);
//设置摩擦力
box->getFixture()->SetFriction(0);
return true;
}
void Box2dTest::draw(){
Layer::draw();
GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION);
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
}