首先是头文件,此笔记是整合在一起的, 不同类别用/*****/分开了
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
//#include <cocos-ext.h> //引入这玩意 需要在配置 C++ -- 常规 --包含引用目录后添加 $(EngineRoot) 使用tableView需要引入此头文件
#include <Box2D\Box2D.h> //box2d head
//USING_NS_CC_EXT; //使用tableview时引入
USING_NS_CC;
#define RATIO 80.0f
class HelloWorld : public cocos2d::Layer,public b2ContactListener //b2ContactListener box2d碰撞检测 //,TableViewDataSource,TableViewDelegate //必须继承此类来实现TableView
{
/*private:
LabelTTF *myLabel;*/
private:
Size visibleSize;
b2World *world;
b2Body *groundBody;
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
//************ 物理引擎 *************/
/*virtual void onEnter();
void addEdges();
void addBox(float x,float y);*/
/***************分割线*********************/
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
/********* 计时器 *********/
virtual void update(float dt); //box2d练习中也用到了此方法
/**************** box2d ********************/
virtual void addRect(float x,float y,b2BodyType type);
void addGround();
virtual void BeginContact(b2Contact* contact);
/// Called when two fixtures cease to touch.
virtual void EndContact(b2Contact* contact);
/*************** 以下均是为实现TableView声明的函数 *****************************************/
/*public:
virtual Size cellSizeForTable(TableView *table);
virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx);
virtual ssize_t numberOfCellsInTableView(TableView *table);
public:
virtual void tableCellTouched(TableView* table, TableViewCell* cell);
virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view){};
virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) {}; **/
/**************************TableView the End ***********************************/
};
#endif // __HELLOWORLD_SCENE_H__
具体实现
#include "HelloWorldScene.h"
//#include <tinyxml2/tinyxml2.h> //解析xml
//#include <json/document.h> //解析json
//#include <ui/CocosGUI.h> //加载cocos studio所需头文件
//#include <cocostudio/CocoStudio.h>
USING_NS_CC;
//碰撞检测所用宏命令
/*
#define RED_BIT_MASK 0x0100
#define GREEN_BIT_MASK 0x0010
#define BLUE_BIT_MASK 0x0001
#define EDGE_BIT_MASK 0x1000*/
/**************************** 以下是自定义TableView的实现函数 *****************************************/
/**
**设置Table的尺寸 Size第二个参数是 每列的高度距离,第一个参数作用未知
**/
/*Size HelloWorld::cellSizeForTable(cocos2d::extension::TableView *table){
return Size(5,50);
}
TableViewCell* HelloWorld::tableCellAtIndex(cocos2d::extension::TableView *table,ssize_t idx){
TableViewCell *cell = table->dequeueCell();
//LabelTTF *label;
Sprite * sprite;
if(cell==NULL){
cell = TableViewCell::create();
sprite = Sprite::create("cell.jpg");
sprite->setTag(2);
sprite->setAnchorPoint(Point(0,0));//设置列 的锚点 不设置会显示不完整
cell->addChild(sprite);
}else{
sprite = (Sprite*)cell->getChildByTag(2);
}
//set data
return cell;
}
ssize_t HelloWorld::numberOfCellsInTableView(cocos2d::extension::TableView *table){
return 100;
} */
/************ Touched Event **************/ //点击TableView事件
/*void HelloWorld::tableCellTouched(cocos2d::extension::TableView *table,TableViewCell *cell){
log("you touched!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
} */
/**************************TableView 函数结束*******************************/
/********************* cocos2dx物理引擎的使用 ****************************/
/*void HelloWorld::onEnter(){
Layer::onEnter();
addBox(visibleSize.width/2,visibleSize.height/2);//添加一个box
addEdges();
CCLOG("init seccess");
auto listener = EventListenerTouchOneByOne::create();//创建事件
listener->onTouchBegan=[this](Touch *t,Event *event){//点击屏幕添加小球
this->addBox(t->getLocation().x,t->getLocation().y);
return false;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);//启动事件侦听
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin=[](PhysicsContact & contact){ //盒子碰撞事件
//碰撞检测
switch(contact.getShapeA()->getBody()->getContactTestBitmask()|contact.getShapeB()->getBody()->getContactTestBitmask()){
case RED_BIT_MASK|BLUE_BIT_MASK://红和蓝相撞
log("red and blue");
break;
case RED_BIT_MASK|GREEN_BIT_MASK://红和绿相撞
log("red and green");
break;
case BLUE_BIT_MASK|GREEN_BIT_MASK://蓝和绿相撞
log("blue and green");
break;
case GREEN_BIT_MASK|EDGE_BIT_MASK://绿色盒子撞墙
log("green hit edge");
break;
case RED_BIT_MASK|EDGE_BIT_MASK://红色盒子撞墙
log("red hit edge");
break;
case BLUE_BIT_MASK|EDGE_BIT_MASK://蓝色盒子撞墙
log("blue hit edge");
break;
case GREEN_BIT_MASK:
log("tow green box");
break;
case RED_BIT_MASK:
log("tow red box");
break;
case BLUE_BIT_MASK:
log("tow blue box");
break;
default:
log("it's not collion");
break;
}
return true; //必须return true否则物理碰撞效果会失效,因事件无法继续传播
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener,this);
}
//添加物理碰撞边界
void HelloWorld::addEdges(){
auto body = PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT,3);
auto edgeShape = Node::create();
edgeShape->setPhysicsBody(body);
edgeShape->getPhysicsBody()->setContactTestBitmask(EDGE_BIT_MASK);
edgeShape->setPosition(visibleSize.width/2,visibleSize.height/2);
addChild(edgeShape);
}*/
//添加碰撞盒子
//void HelloWorld::addBox(float x,float y){
/*auto ball = Sprite::create("ball.png"); //添加可碰撞的精灵
ball->setPhysicsBody(PhysicsBody::createBox(ball->getContentSize()));//设置碰撞体积为图片本身大小
ball->setPosition(x,y);
addChild(ball);*/
//添加碰撞盒子
/*auto box = Sprite::create();
box->setTextureRect(Rect(0,0,50,50));//设置盒子宽高
box->setPhysicsBody(PhysicsBody::createBox(box->getContentSize()));//设置碰撞体积
addChild(box);
box->setPosition(x,y);
switch(rand()%3){
case 0:
box->setColor(Color3B(255,0,0));
box->getPhysicsBody()->setContactTestBitmask(RED_BIT_MASK);
break;
case 1:
box->setColor(Color3B(0,255,0));
box->getPhysicsBody()->setContactTestBitmask(GREEN_BIT_MASK);
break;
case 2:
box->setColor(Color3B(0,0,255));
box->getPhysicsBody()->setContactTestBitmask(BLUE_BIT_MASK);
break;
}
} */
/********************** 物理引擎结束分割线 ******************************/
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
/********************* cocos2dx物理引擎的使用 ****************************/
/*auto scene = Scene::createWithPhysics(); //要使用物理引擎必须使用此初始化屏幕
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
scene->getPhysicsWorld()->setGravity(Vec2(0,-1000));//设置物体的掉落速度*/
/***********物理引擎分割线******************/
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//
// 1. super init first
if ( !Layer::init() )
{
return false;
}
visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//self code show sprite
//普通移动精灵
/*auto sprite = Sprite::create("HelloWorld.png");
sprite->setPosition(visibleSize/2);
sprite->setPositionX(100);
sprite->setScale(0.5); //缩放
this->addChild(sprite);
sprite->runAction(MoveTo::create(2,Vec2(visibleSize.width-100,visibleSize.height/2))); //移动action*/
/******************** 动作 ***************************/
//顺序执行动作
/*auto move1 = MoveTo::create(2,Vec2(visibleSize.width-100,visibleSize.height/2));
auto move2 = MoveBy::create(2,Vec2(-700,0));
sprite->runAction(Sequence::create(move1,move2,NULL));*/
//顺序执行动作方式2
/*auto move1=MoveBy::create(2,Vec2(700,0));
auto move2=move1->reverse();
sprite->runAction(Sequence::create(move1,move2,NULL));*/
//并列执行动作
/*auto move = MoveBy::create(2,Vec2(700,0));
auto scale = ScaleTo::create(2,1);
//sprite->runAction(Spawn::create(move,scale,NULL));
//动作执行完毕回调函数
sprite->runAction(Sequence::create(Spawn::create(move,scale,NULL),CallFunc::create([](){
CCLOG("action complete");
}),NULL));*/
/******************************特效***************************************/
//抖动特效
/*auto role=NodeGrid::create();
role->addChild(Sprite::create("HelloWorld.png"));
role->setPosition(visibleSize/2);
addChild(role);*/
//抖动特效 参数1是抖动时间 参数3是抖动程度
//role->runAction(Shaky3D::create(10,Size(50,50),5,false));
//网格特效 size :切割50X50块 5:执行5秒
//role->runAction(ShakyTiles3D::create(10,Size(50,50),5,false));
//爆炸特效 参数1是爆炸时间 其余未知
//role->runAction(ShuffleTiles::create(1,Size(50,50),5));
//顺序执行先抖动再爆炸效果
/*auto doudong = Shaky3D::create(1,Size(50,50),10,false);
auto baozha = ShuffleTiles::create(1,Size(50,50),5);
role->runAction(Sequence::create(doudong,baozha,NULL));*/
//碎片消失效果
//role->runAction(TurnOffTiles::create(1,Size(50,50),25));
//波纹效果
//role->runAction(Waves3D::create(2,Size(15,10),5,40));
//波纹效果执行完毕后恢复原来效果
/*auto w1 = Waves3D::create(2,Size(15,10),5,40);
auto w2 = Waves3D::create(2,Size(15,10),5,0);
role->runAction(Sequence::create(w1,w2,NULL));*/
/***************************************场景切换特效**************************************/
/*auto background = Sprite::create("bg.jpg");
background->setPosition(visibleSize/2);
addChild(background);
//创建文字
/*LabelTTF *label = LabelTTF::create("more eat with the shit!Dou Bi Song!", "Consolas", 40);
label->setPosition(visibleSize.width / 2, visibleSize.height / 2);
addChild(label);*/
/*scheduleOnce([visibleSize](float f){
auto newScene = Scene::create();
auto newBackground = Sprite::create("bg2.jpg");
newBackground->setPosition(visibleSize/2);
newScene->addChild(newBackground);
//创建特效
//auto t = TransitionCrossFade::create(1,newScene); //淡出切换效果
//auto t = TransitionZoomFlipAngular::create(1,newScene);//反转特效
//auto t = TransitionPageTurn::create(1,newScene,false);//翻页特效 true and false切换不同翻页特效
//auto t = TransitionProgressRadialCW::create(1,newScene); //顺时针特效
auto t = TransitionSplitRows::create(1,newScene);//拆分特效
Director::getInstance()->replaceScene(t);//执行特效
},2,"Test");*/
/*******************timer**************************************/
//scene change
/*scheduleOnce([visibleSize,this](float f){ //三秒后执行下列代码
auto scene2 = Scene::create();
auto scene2Layer = Layer::create();
scene2->addChild(scene2Layer);
auto logo = Sprite::create("HelloWorld.png");
logo->setPosition(visibleSize/2);
scene2Layer->addChild(logo);
Director::getInstance()->replaceScene(scene2);
},3,"testMethod");*/
/**********************Vector*******************************/
/*Vector<Label*> v; //只能存放继承ref的对象
auto label=Label::create();
auto label2 =Label::create();
label ->setString("label 1");
label2->setString("label 2");
label->setSystemFontSize(50);
label2->setSystemFontSize(50);
v.pushBack(label);
v.pushBack(label2);
int i = 0;
for (auto l:v)
{
i++;
l->setPosition(Vec2(visibleSize.width/2,i*200));
addChild(l);
}*/
/*************************** Table View ***********************************/
/*TableView *tableView = TableView::create(this, Size(200,350)); //Size的第二个参数是 table的高度,第一个参数是table宽度
// tableView->setDirection(ScrollViewDirectionVertical);
tableView->setAnchorPoint(Point(0,0));
tableView->setPosition(400,0);//xy坐标
tableView->setDelegate(this);
//tableView->setVerticalFillOrder(TableViewFillTopDown);
this->addChild(tableView);*/
/******************** Animation 动画 **************************************/
/*auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("testFlash.plist");
Vector<SpriteFrame*> v;
char name[20];
memset(name,0,15);//clear?;
for (int i = 0; i < 15; i++)
{
sprintf(name,"testFlash%04d",i); //%04d 表示是数字且数字为4位 不够的用 0 填充
v.pushBack(cache->getSpriteFrameByName(name));
}
Animation *animation = Animation::createWithSpriteFrames(v,0.1f); //0.1f是帧率
Animate *animate = Animate::create(animation);
auto sprite = Sprite::create();
addChild(sprite);
sprite->setPosition(500,300);
sprite->runAction(RepeatForever::create(animate)); //运行循环特效*/
/******************* 用户交互:触摸,按键... ***************************/
/*auto label = LabelTTF::create("click me!","Courier",30);
label->setPosition(visibleSize.width/2,visibleSize.height/2);
addChild(label);
auto listener = EventListenerTouchOneByOne::create(); //创建监听器
listener->onTouchBegan = [](Touch *touch,Event *event){ //设置监听函数
if(event->getCurrentTarget()->getBoundingBox().containsPoint(touch->getLocation())){ //判断点击范围是在label上
log("onTouched!!!!!!!!!!!!");
}
return true; //返回true才能出发事件传递
};
//事件传递
listener->onTouchMoved = [](Touch* touch,Event *event){ //拖动事件 onTouchEnded = 触摸弹起事件
log("onTouchmoved!");
return true;//返回 true 才可以继续传递事件
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,label); //绑定监听事件 */
//多点触摸监听器******************************************
/*auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = [](std::vector<Touch*> t,Event *event){ //单击事件
log("onTouchesBegan");
};
listener->onTouchesMoved = [](std::vector<Touch*> t,Event *event){ //多点同时触摸事件
log("touches moved,and touch count is%ld",t.size());
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this); */
/**************************** 传感器 *****************************************/
/*Device::setAccelerometerEnabled(true);//打开传感器侦听 传感器=重力感应?
auto listener = EventListenerAcceleration::create([](Acceleration *a,Event *event){
log("x:%g,y:%g,z:%g",a->x,a->y,a->z);
});
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);*/
/************************** 按键监听 ************************************/
/*auto listener = EventListenerKeyboard::create();
listener->onKeyReleased = [](EventKeyboard::KeyCode code,Event *venet){ //监听按键事件
log("key:%d",code);
switch(code){
case EventKeyboard::KeyCode::KEY_BACKSPACE: //如果是后退键
Director::getInstance()->end(); //退出当前程序
break;
}
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);*/
/******** 计时器 ****************/
/*myLabel = LabelTTF::create("hello world","Courier",30);
addChild(myLabel);
scheduleUpdate();//启动计时器??*/
/********** 首选项数据存储 **************/
/*UserDefault::getInstance()->setStringForKey("value","i'm is value");
log(UserDefault::getInstance()->getStringForKey("value","not value!").c_str());//第二个参数是默认值*/
/************** cocos2dx文件读写 *****************************/
//auto fu = FileUtils::getInstance();
/*FILE *file = fopen(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str(),"w"); //写入文件
fprintf(file,"Hello world\n");
log(fu->getWritablePath().c_str());
fclose(file);*/
/*Data data = fu->getDataFromFile(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()));
log("%s",data.getBytes());*/
//*****************plist 文件操作
/*ValueMap map = fu->getValueMapFromFile("testFlash.plist");
log("value is:%s",map["frames"].asString().c_str());*/
/******************* cocos2d的XML文件操作 ****************************/
/*auto document = new tinyxml2::XMLDocument();
document->Parse(fu->getStringFromFile("data.xml").c_str());
auto root = document->RootElement();
log("parse xml begin");
for (auto e = root->FirstChildElement(); e; e=e->NextSiblingElement())
{
std::string str;
log("node name is:%s",e->Value());
for (auto attr = e->FirstChildElement();attr;attr=attr->NextSiblingElement())
{
str+=attr->Name(); //节点名称
str+=":";
str+=attr->GetText(); //节点值
str+="\n";
}
log("%s",str.c_str());
}*/
//*********************** 解析json数据 ************************************/
/*rapidjson::Document d;
d.Parse<0>(FileUtils::getInstance()->getStringFromFile("jsonName.json").c_str());
log("%s",d.[(int)0]["name"]);//获取json的name属性值*/
/***************** 加载TMX地图 *****************************/
/*auto map = TMXTiledMap::create("map.tmx");
addChild(map);
auto p = map->getProperties();
auto str = p["type"].asString();
log("map attr:%s",str);
//获取图层属性
auto l = map->getLayer("scane");
auto lp = l->getProperties();
log("layer attr:%s",lp["type"].asString().c_str());
//获取图块属性
auto tile = map->propertiesForGID(1).asValueMap();
log("tile attr:%s",tile["type"].asString().c_str());
//对象属性
auto o = map->getObjectGroup("object");
auto obj = o->getObject("player");
log("object attr:%s",obj["type"].asString().c_str()); //获取palyer出生点同理
//修改指定区域颜色
auto co = o->getObject("color");
auto x = co["x"].asInt()/32;
auto y = co["y"].asInt()/32;
auto w = co["width"].asInt()/32;
auto h = co["height"].asInt()/32;//why /32
for (int i = x; i < x+w; i++)
{
for (int j = y; j < y+h; j++)
{
auto sprite = l->getTileAt(Vec2(i,map->getMapSize().height-j)); //tile map 的x Y轴是相反的
sprite->setColor(Color3B(255,0,0));
}
}
Sprite *player = Sprite::create("player.png");
player->setPosition(obj["x"].asFloat(),obj["y"].asFloat());
addChild(player);
auto eventListener = EventListenerTouchOneByOne::create();
eventListener->onTouchBegan = [map,l,player](Touch *touch,Event *event){ //添加点击事件来模拟玩家移动
auto point = map->convertToNodeSpace(touch->getLocation()); //获得点击的位置
point.x = static_cast<int>(point.x/32); //点击的位置感觉有偏差 可能是tilemap没画好
point.y = map->getMapSize().height-static_cast<int>(point.y/32)-1;
auto t = l->getTileAt(point);
//t->setColor(Color3B(255,0,0));
auto gid = l->getTileGIDAt(point); //获取GID
auto p = map->getPropertiesForGID(gid).asValueMap();
if(!p["move"].isNull()&&p["move"].asBool()){ //判断点击位置是否在可移动范围内
player->setPosition(t->getPosition().x,t->getPosition().y);//将player移动到点击的位置
}
return false;
};
//注册侦听事件
_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener,map);*/
/********************* cocos studio 加载 ***********************/
/*auto node = CSLoader::createNode("MainMenu.csb");
addChild(node);*/
//获取容器示例
//auto pageView = node->getChildByName<ui::PageView>("PageView");
//序列化框架:FlatBuffers
//使用plist载入cocos studio。
/*SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Plist.plist");//如使用资源文件 则不需要此行代码
//翻页容器示例
auto levelSelection = CSLoader::createNode("Layer.csb");
addChild(levelSelection);
//获取翻页容器
auto pageView = levelSelection->getChildByName<ui::PageView*>("PageView_SelectPage");
//左按钮
auto leftButton = levelSelection->getChildByName<ui::Button*>("Button_Left");
auto rightButton = levelSelection->getChildByName<ui::Button*>("Button_Right");
//获得Label控件
//auto levelNumber = levelSelection->getChildByName<ui::TextAtlas*>("LabelAtlas_CurrentScene");//不知为何拿不到该控件
log("lode complete");
//添加滑动监听事件
pageView->addEventListener([pageView](Ref* ref,ui::PageView::EventType type){
if(type==ui::PageView::EventType::TURNING){
//levelNumber->setString(StringUtils::format("%zd/3",pageView->getCurPageIndex()+1));//滑动修改label控件显示的字符串
}
});
//按钮事件
leftButton->addClickEventListener([pageView](Ref* ref){
auto index = pageView->getCurPageIndex();
index--;
if(index<0){
return;
}
pageView->scrollToPage(index);
});
rightButton->addClickEventListener([pageView](Ref* ref){
auto index = pageView->getCurPageIndex();
index++;
if(index>3){
return;
}
pageView->scrollToPage(index);
}); */
//**********加载cocos studio动画
/*auto rootNode = CSLoader::createNode("AnimationScene.csb");
rootNode->setPosition(visibleSize/8);//本来应该是/2居中的 可能应为窗口大小原因位置不正确
addChild(rootNode);
auto timeLine = CSLoader::createTimeline("AnimationScene.csb");
timeLine->gotoFrameAndPlay(0,45+1,true);//设置播放方式 如不设置从多少帧到多少帧则无法监听到最后一帧的事件(不知为何。。); true表示循环播放,必须最后一帧+1才能完整监听所有事件,不知为何。。
rootNode->runAction(timeLine);
//监听动画的帧事件
timeLine->setFrameEventCallFunc([](cocostudio::timeline::Frame* frame){
auto event = dynamic_cast<cocostudio::timeline::EventFrame*>(frame);
if(event!=nullptr){ //如果当前帧不为空
CCLOG("%s",event->getEvent().c_str()); //输出当前帧名称
}
});*/
/********************** cocos studio the end ************************/
/*************************************** Box2D **************************************************/
world = new b2World(b2Vec2(0,-10)); //创建box2d物理世界 参数分别是x y轴的重力 y 轴-10 表示往下掉落 速度为10
world->SetContactListener(this);
addRect(5, 3, b2_dynamicBody); //b2_dynamicBody 动态物体 b2_staticBody静态物体 b2_kinematicBody漂浮物体
addGround();
scheduleUpdate();
return true;
}
/******** 计时器练习 和 Box2d练习 ****************/
void HelloWorld::update(float dt){
//myLabel->setPosition(myLabel->getPosition()+Point(1,1)); //计时器
/************* box2d **************/
world->Step(dt,8,3);
Sprite *s;
for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()){
if (b->GetUserData()){
s = (Sprite*)b->GetUserData();
s->setPosition(b->GetPosition().x*RATIO,b->GetPosition().y*RATIO);//每次渲染都让sprite与box body保持位置绑定
}
}
}
/******************************* box2d练习 *************************/
void HelloWorld::addRect(float x,float y,b2BodyType type){
b2BodyDef def;
def.position = b2Vec2(x,y);
def.linearVelocity = b2Vec2(0,10);//运动物体 第一个参数是x轴 第二个参数是y轴 必须是漂浮物体或者动态物体
def.type = type;//b2_dynamicBody 是动态物体(枚举)
b2Body *body = world->CreateBody(&def);
b2PolygonShape shape;
shape.SetAsBox(0.5,0.5);
b2FixtureDef fixtureDef;
fixtureDef.density = 1;
fixtureDef.friction = 0.3;
fixtureDef.shape = &shape;
body->CreateFixture(&fixtureDef);
//创建盒子图像以显示物理下落效果
auto sprite = Sprite::create();
sprite->setTextureRect(Rect(0,0,0.5*2*RATIO,0.5*2*RATIO));
addChild(sprite);
sprite->setPosition(Point(def.position.x*RATIO,def.position.y*RATIO));//物理物体会自动往下掉 因此绑定物理物体的位置到sprite上 就形成了物理
body->SetUserData(sprite);//body与sprite图形绑定
}
void HelloWorld::addGround(){
b2BodyDef def;
def.position = b2Vec2(400/RATIO,0);
def.type = b2_staticBody;//设置类型为静态物体
groundBody = world->CreateBody(&def);
b2PolygonShape groundShape;
groundShape.SetAsBox(400/RATIO,0.5);
b2FixtureDef fixureDef;
fixureDef.density = 1;
fixureDef.friction = 0.3;
fixureDef.shape = &groundShape;
groundBody->CreateFixture(&fixureDef);
}
void HelloWorld::BeginContact(b2Contact* contact) {
if (contact->GetFixtureA()->GetBody() == groundBody || contact->GetFixtureB()->GetBody() == groundBody){
log("floor touched");
}
}
void HelloWorld::EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
void HelloWorld::menuCloseCallback(Ref* pSender)
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}