【转自】:http://www.cocoachina.com/bbs/read.php?tid=209290 

 

 工具介绍,json文件获得方法,请参考原帖

 MyBodyParser.h

 //
// MyBodyParser.h
//
// Created by Jason Xu.
//
// #pragma once #include <string>
#include "cocos2d.h"
USING_NS_CC;
#include "json/document.h" class MyBodyParser {
MyBodyParser(){}
rapidjson::Document doc;
public:
static MyBodyParser* getInstance();
bool parseJsonFile(const std::string& pFile);
bool parse(unsigned char* buffer, long length);
void clearCache();
PhysicsBody* bodyFormJson(Node* pNode, const std::string& name);
};

 MyBodyParser.cpp

 

 //
// MyBodyParser.cpp
//
// Created by Jason Xu.
//
// #include "MyBodyParser.h" MyBodyParser* MyBodyParser::getInstance()
{
static MyBodyParser* sg_ptr = nullptr;
if (nullptr == sg_ptr)
{
sg_ptr = new MyBodyParser;
}
return sg_ptr;
} bool MyBodyParser::parse(unsigned char *buffer, long length)
{
bool result = false;
std::string js((const char*)buffer, length);
doc.Parse<>(js.c_str());
if(!doc.HasParseError())
{
result = true;
}
return result;
} void MyBodyParser::clearCache()
{
doc.SetNull();
} bool MyBodyParser::parseJsonFile(const std::string& pFile)
{
auto content = FileUtils::getInstance()->getDataFromFile(pFile);
bool result = parse(content.getBytes(), content.getSize());
return result;
} //从json文件加载正确的body
PhysicsBody* MyBodyParser::bodyFormJson(cocos2d::Node *pNode, const std::string& name)
{
PhysicsBody* body = nullptr;
rapidjson::Value &bodies = doc["rigidBodies"];
if (bodies.IsArray())
{
//遍历文件中的所有body
for (int i=; i<bodies.Size(); ++i)
{
//找到了请求的那一个
if ( == strcmp(name.c_str(), bodies[i]["name"].GetString()))
{
rapidjson::Value &bd = bodies[i];
if (bd.IsObject())
{
//创建一个PhysicsBody, 并且根据node的大小来设置
body = PhysicsBody::create();
float width = pNode->getContentSize().width;
float offx = - pNode->getAnchorPoint().x*pNode->getContentSize().width;
float offy = - pNode->getAnchorPoint().y*pNode->getContentSize().height; Point origin( bd["origin"]["x"].GetDouble(), bd["origin"]["y"].GetDouble());
rapidjson::Value &polygons = bd["polygons"];
for (int i = ; i<polygons.Size(); ++i)
{
int pcount = polygons[i].Size();
Point* points = new Point[pcount];
for (int pi = ; pi<pcount; ++pi)
{
points[pi].x = offx + width * polygons[i][pcount--pi]["x"].GetDouble();
points[pi].y = offy + width * polygons[i][pcount--pi]["y"].GetDouble();
}
body->addShape(PhysicsShapePolygon::create(points, pcount, PHYSICSBODY_MATERIAL_DEFAULT));
delete [] points;
}
}
else
{
CCLOG("body: %s not found!", name.c_str());
}
break;
}
}
}
return body;
}

 HelloWorldScene.cpp (测试cpp)

 #include "HelloWorldScene.h"
#include "MyBodyParser.h"
USING_NS_CC; Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics(); //enable debug draw
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); // '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;
} Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin(); /////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it. // add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/ ,
origin.y + closeItem->getContentSize().height/)); // create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Point::ZERO);
this->addChild(menu, ); /////////////////////////////
// 3. add your codes below... // add a label shows "Hello World"
// create and initialize a label auto label = LabelTTF::create("Physics Body Loader Demo", "Arial", ); // position the label on the center of the screen
label->setPosition(Point(origin.x + visibleSize.width/,
origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer
this->addChild(label, ); status_label = LabelTTF::create("Touch anywhere!", "Arial", );
status_label->setPosition(Point(origin.x + visibleSize.width/, 1.2*status_label->getContentSize().height));
this->addChild(status_label); // add "2dx.png"
sp_2dx = Sprite::create("2dx.png"); // position the sprite on the center of the screen
sp_2dx->setPosition(Point(visibleSize.width/ + origin.x, visibleSize.height/ + origin.y)); //load
MyBodyParser::getInstance()->parseJsonFile("bodies.json"); //bind physicsbody to sprite
auto _body = MyBodyParser::getInstance()->bodyFormJson(sp_2dx, "2dx");
if (_body != nullptr) {
_body->setDynamic(false); //set it static body.
_body->setCollisionBitmask(0x000000); //don't collision with anybody.
sp_2dx->setPhysicsBody(_body);
} // add the sprite as a child to this layer
this->addChild(sp_2dx, ); //add touchListener
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); return true;
} Node* HelloWorld::nodeUnderTouch(cocos2d::Touch *touch)
{
Node* node = nullptr;
//转换到layer内的坐标
auto location = this->convertTouchToNodeSpace(touch);
//得到当前点下方的物理shapes
auto scene = Director::getInstance()->getRunningScene();
auto arr = scene->getPhysicsWorld()->getShapes(location); //遍历当前点击到的所有shapes, 看看有没有我们的2dx!
for (auto& obj : arr)
{
//find it
if ( obj->getBody()->getNode() == sp_2dx)
{
node = obj->getBody()->getNode();
break;
}
}
return node;
} bool HelloWorld::onTouchBegan(Touch* touch, Event* event)
{
auto current_node = nodeUnderTouch(touch); //get it!
if (current_node == sp_2dx)
{
status_label->setColor(Color3B::GREEN);
status_label->setString("Ohoo, U catch me!");
}
else
{
status_label->setColor(Color3B::RED);
status_label->setString("Haha, touch outside!");
} return true;
} void HelloWorld::onTouchMoved(Touch* touch, Event* event)
{
} void HelloWorld::onTouchEnded(Touch* touch, Event* event)
{
status_label->setColor(Color3B::WHITE);
status_label->setString("Touch anywhere!");
} void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit();
#endif
}

 

使用Physics_Body_Editor获得json文件的类的更多相关文章

  1. .NetCore读取配置Json文件到类中并在程序使用

    ConfigurationBuilder 这个类提供了配置绑定,在dnc中 Program中WebHost提供了默认的绑定(appsettings文件) 如果我们需要加载我们自己的json配置文件怎么 ...

  2. 第三天,爬取伯乐在线文章代码,编写items.py,保存数据到本地json文件中

        一. 爬取http://blog.jobbole.com/all-posts/中的所有文章     1. 编写jobbole.py简单代码 import scrapy from scrapy. ...

  3. Code片段 : .properties属性文件操作工具类 & JSON工具类

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 j ...

  4. 使用maven根据JSON文件自动生成Java POJO类(Java Bean)源文件

    根据JSON文件自动生成Java POJO类(Java Bean)源文件 本文介绍使用程序jsonschema2pojo来自动生成Java的POJO类源文件,本文主要使用maven,其他构建工具请参考 ...

  5. .net core2.0添加json文件并转化成类注入控制器使用

    上一篇,我们介绍了如何读取自定义的json文件,数据是读取出来了,只是处理的时候太麻烦,需要一遍一遍写,很枯燥.那么有没有很好的办法呢?经过钻研,办法有了. 既然一个一个读取比较麻烦,那么可以把它放入 ...

  6. 自定义mysql类用于快速执行数据库查询以及将查询结果转为json文件

    由于每次连接数据库进行查询比较麻烦,偶尔还需要将查询结果转为json格式的文件, 因此暂时定义一个mysql的类,将这些常用的方法进行封装,便于直接调用(代码如下,个人用,没写什么注释). 注:导入了 ...

  7. C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题

    C#字符串数组排序   //排序只带字符的数组,不带数字的 private   string[]   aa   ={ "a ", "c ", "b & ...

  8. .net core2.0添加json文件并转化成类注入控制器使用 让js调试更简单—console

    .net core2.0添加json文件并转化成类注入控制器使用 上一篇,我们介绍了如何读取自定义的json文件,数据是读取出来了,只是处理的时候太麻烦,需要一遍一遍写,很枯燥.那么有没有很好的办法呢 ...

  9. ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下

    ADO.NET   一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data  → DataTable, ...

随机推荐

  1. 网络流CodeForces. Original 589F:Gourmet and Banquet

    A gourmet came into the banquet hall, where the cooks suggested n dishes for guests. The gourmet kno ...

  2. excel小技巧-用于测试用例的编号栏:“获取当前单元格的上一格的值+1”=INDIRECT(ADDRESS(ROW()-1,COLUMN()))+1

    编写用例的时候使用,经常修改用例的时候会需要增加.删除.修改条目,如果用下拉更新数值的方式会很麻烦. 1.使用ctrl下拉,增删移动用例的时候,需要每次都去拉,万一列表比较长,会很麻烦 2.使用ROW ...

  3. lr 和 Qtp 视频连接

    http://blog.sina.com.cn/s/blog_7085382f01012ysn.html

  4. JavaScript高级程序设计19.pdf

    注册处理程序 navigator.registerContentHandler("applicat/rss+xml","http://www.somereader.com ...

  5. 龙芯8089_D安装debian 8 iessie

    参考官方文档:https://wiki.debian.org/DebianYeeloong/HowTo/Install 下载网络引导文件后使用tftpd建立ftfp服务器,然后使用PMON tftp来 ...

  6. HDU 1230 火星A+B

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1230 水题模拟一道,主要考验代码能力,刷完题就感觉自己还是太弱了. #include<cmath ...

  7. hdu 4432 Sum of divisors(十进制转其他进制)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4432 代码: #include<cstdio> #include<cstring&g ...

  8. poj 3465 Corn Fields 状态压缩

    题目链接:http://poj.org/problem?id=3254 #include <cstdio> #include <cstring> #include <io ...

  9. tomacat 配置ssl协议

    1.首先用jdk自带的工具keytool生成一个"服务器证书" a.命令行进入$JAVA_HOME/bin目录($JAVA_HOME为jdk的安装目录) b.输入:keytool ...

  10. cocoaPods教程

    <#这个不是命令,包括尖括号#> 一.源设置 1. 查看源,终端输入:  sudo gem sources -l 2. 删除已有的源,如:  sudo gem sources --remo ...