【转自】: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. OC语言中类目,延展,协议

    一.类目 指向已知的类中添加新方法,不破坏封装性.已知类可以是自定义的类和系统的类. 1.类目的实现和声明 建一个学生类,并增加类目 (1).声明(是在Student+Working.h中) 必须引入 ...

  2. 神器 Sublime Text 3 的一些常用快捷键

    选择类   Ctrl+D 选中光标所占的文本,继续操作则会选中下一个相同的文本. Alt+F3 选中文本按下快捷键,即可一次性选择全部的相同文本进行同时编辑.举个例子:快速选中并更改所有相同的变量名. ...

  3. [zz]android的logcat详细用法

    Android日志系统提供了记录和查看系统调试信息的功能.日志都是从各种软件和一些系统的缓冲区中记录下来的,缓冲区可以通过 logcat 命令来查看和使用.      一.使用logcat命令的目的: ...

  4. centos7免密码登录

    2台主机 192.168.30.207 Master 192.168.30.251 Node1 三台主机检查 ~/.ssh 文件夹没有则新建 ssh-keygen -t rsa 一路狂按回车,最终生成 ...

  5. iOS-实现映客首页TabBar和滑动隐藏NavBar和TabBar

    之前在做直播的时候,参照了映客App,发现其首页的效果还挺不错,在网上找了一下相关仿映客App代码和博客,大部分都是说如何播放直播流和推流,对于UI这块甚少,所以我自己花了点时间研究了一下映客的首页U ...

  6. weblogic下 微信公众平台获取token报错

    问题描述: 开发微信公众平台,本地tomcat可以正常获取token并发送模板消息,部署在weblogic后报错,异常信息如下: java.security.InvalidKeyException: ...

  7. web项目学习之基于注解的Controller

    1. 低版本Spring MVC 实现Controller 使用过低版本 Spring MVC 的读者都知道:当创建一个 Controller 时,我们需要直接或间接地实现 org.springfra ...

  8. 【Android - 进阶】之MultiDex的配置

    一.什么是MultiDex 随着时代的进步,人们对手机 APP 的需求越来越大,越来越苛刻,很多APP都变得很大,再加上APP都不可避免的需要导入一些框架.第三方类库等等,就更加大了项目的整体文件体系 ...

  9. Unity3d UnityEditor EditorWindow 自定义窗体控件

    功能:是因为公司的模型组需要一个插件,在MAYA中有很多个复制物体,导出的时候只导出一个,其他相同的物体只导出点的位置信息.这样进入Unity里就是一个物体和N个相同物体的位置点,代码简单但是需要用插 ...

  10. oracle正则截取字符串的函数

    现在有这么一个需求, 数据库中的一个手输的'籍贯'字段,要按一定的规范截取显示在报表上,比如,如果'籍贯'的内容是:'山东省潍坊市昌乐县', 那么报表里要显示为:'山东昌乐', 如果'籍贯'是山东省潍 ...