#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "cocostudio/CocoStudio.h" #include "ui/CocosGUI.h" USING_NS_CC; class HelloWorld : public cocos2d::Layer { private: Vector<Sprite *>SP; Sprite *touchedS; public: 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 bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); virtual void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); virtual void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); void addNewSpriteAtPosition(cocos2d::Vec2 p); // implement the "static create()" method manually CREATE_FUNC(HelloWorld); }; #endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h" using namespace cocostudio::timeline; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::createWithPhysics(); //建立物理場景 scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); scene->getPhysicsWorld()->setGravity(Vec2(0,-100)); //設置重力方向 // '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; } Vec2 location; touchedS = nullptr; location.x = 100 + 50; location.y = 500; addNewSpriteAtPosition(location); //首先建立一個精靈 Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //定義世界的邊界 auto body = PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT, 1.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) { auto location = touch->getLocation(); for (auto sp : SP) { if (sp->getBoundingBox().containsPoint(location)) { touchedS = sp; //touchedS->getPhysicsBody()->setDynamic(false); return true; //若是點擊的是精靈 則獲取當前精靈 不然建立新的精靈 } } addNewSpriteAtPosition(location); return true; } void HelloWorld::onTouchMoved(Touch* touch, Event* event) { if (touchedS != nullptr) { touchedS->setPosition(touch->getLocation()); } } void HelloWorld::onTouchEnded(Touch * touch,Event * event) { if (touchedS != nullptr) { //touchedS->getPhysicsBody()->setDynamic(true); touchedS = nullptr; } } void HelloWorld::addNewSpriteAtPosition(Vec2 p) { auto sp = Sprite::create("HelloWorld.png"); sp->setTag(1); auto body = PhysicsBody::createCircle(sp->getContentSize().width / 2); sp->setPhysicsBody(body); sp->setPosition(p); sp->setScale(0.05); this->addChild(sp); SP.pushBack(sp); }