最近期中考又偷懒了几天。啧啧啧
今天来看看cocos2dx的物理引擎。这里要实现的效果很简单,如下
直接上代码
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
void addNewSpriteAtPosition(cocos2d::Vec2 p);
bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
auto scene= HelloWorld::createWithPhysics();
PhysicsWorld* pw=scene->getPhysicsWorld();
pw->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
auto layer=HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !Scene::init() )
{
return false;
}
auto 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);
auto dispatcher = Director::getInstance()->getEventDispatcher();
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
listener->setSwallowTouches(true);//不向下传递触摸
dispatcher->addEventListenerWithSceneGraphPriority(listener,this);
return true;
}
bool HelloWorld::onTouchBegan(Touch* touch, Event* event)
{
Vec2 location = touch->getLocation();
addNewSpriteAtPosition(location);
return false;
}
void HelloWorld::addNewSpriteAtPosition(Vec2 p)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto boxA = Sprite::create("BoxA2.png");
boxA->setPosition(origin+ p);
auto boxABody = PhysicsBody::createBox(boxA->getContentSize());
boxA->setPhysicsBody(boxABody);
this->addChild(boxA, 10, 100);
auto boxB = Sprite::create("BoxB2.png");
boxB->setPosition(origin + p + Vec2(0, -120));
auto boxBBody = PhysicsBody::createBox(boxB->getContentSize());
boxB->setPhysicsBody(boxBBody);
this->addChild(boxB, 20, 101);
auto world = this->getScene()->getPhysicsWorld();
PhysicsJointDistance* joint = PhysicsJointDistance::construct(boxABody, boxBBody,Vec2(0, 0), Vec2(0, boxB->getContentSize().width / 2));
world->addJoint(joint);
}
好了就到这里了,DRW