#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); ①
CREATE_FUNC(HelloWorld);
void addNewSpriteAtPosition(Vec2 p); ②
};
#endif // __HELLOWORLD_SCENE_H__Scene* HelloWorld::createScene()
{
auto scene = Scene::createWithPhysics(); ①
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); ②
auto layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//定义世界的边界
auto body = PhysicsBody::createEdgeBox(visibleSize,
PHYSICSBODY_MATERIAL_DEFAULT,5.0f); ①
auto edgeNode = Node::create(); ②
edgeNode->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2)); ③
edgeNode->setPhysicsBody(body); ④
this->addChild(edgeNode); ⑤
setTouchEnabled(true); ⑥
//设置为单点触摸
setTouchMode(Touch::DispatchMode::ONE_BY_ONE); ⑦
return true;
}bool HelloWorld::onTouchBegan(Touch* touch, Event* event) ①
{
Vec2 location = touch->getLocation();
addNewSpriteAtPosition(location);
return false;
}
void HelloWorld::addNewSpriteAtPosition(Vec2 p) ②
{
auto sp = Sprite::create("Ball.png"); ③
sp->setTag(1); ④
auto body = PhysicsBody::createCircle(sp->getContentSize().width / 2); ⑤
//auto body = PhysicsBody::createBox(sp->getContentSize()); ⑥
sp->setPhysicsBody(body); ⑦
sp->setPosition(p);
this->addChild(sp);
}第⑥行代码PhysicsBody::createBox(sp->getContentSize())是创建一个没有边的矩形盒子。第⑦行代码sp->setPhysicsBody(body)是设置与精灵相关的物体对象。
欢迎关注智捷iOS课堂微信公共平台
实例介绍Cocos2d-x物理引擎:HelloPhysicsWorld
原文地址:http://blog.csdn.net/tonny_guan/article/details/39482331