1 // 2 // GameScene.hpp 3 // HelloWord 4 // 5 // Created by apple on 2017/1/7. 6 // 7 // 8 9 #ifndef GameScene_hpp10 #define GameScene_hpp11 12 #include13 #include "cocos2d.h"14 15 USING_NS_CC;16 17 class GameScene : public cocos2d::Layer18 {19 public:20 static cocos2d::Scene* createScene();21 22 virtual bool init();23 24 //重力感应回调函数25 void didAccelerate(Acceleration* acc, Event* event);26 27 CREATE_FUNC(GameScene);28 29 private: 30 Size size;31 Sprite *sprite;32 };33 #endif /* GameScene_hpp */
1 // 2 // GameScene.cpp 3 // HelloWord 4 // 5 // Created by apple on 2017/1/7. 6 // 7 // 8 9 #include "GameScene.hpp"10 USING_NS_CC;11 12 cocos2d::Scene* GameScene::createScene()13 {14 auto scene = Scene::create(); //创建一个场景15 auto layer = GameScene::create(); //创建一个图层16 scene->addChild(layer);17 return scene;18 }19 20 //初始化当前的图层21 bool GameScene::init()22 {23 if(!Layer::init()) //初始化父类24 return false;25 26 //获取屏幕大小27 size = Director::getInstance()->getVisibleSize();28 //auto size = Director::getInstance()->getWinSize();29 //添加一个图片精灵30 sprite = Sprite::create("CloseNormal.png");31 sprite->setPosition(Vec2(size.width/2, size.height/2));32 sprite->setTag(12);33 this->addChild(sprite);34 35 //开启重力感应36 Device::setAccelerometerEnabled(true);37 38 //创建事件监听对象39 auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(GameScene::didAccelerate, this));40 41 //在事件监听器中注册42 _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);43 44 return true;45 }46 47 void GameScene::didAccelerate(Acceleration* acc, Event* event)48 {49 //使精灵随重力感应移动50 auto sprite = this->getChildByTag(12); //通过标签获取精灵51 52 auto pos = sprite->getPosition();53 54 pos.x += acc->x;55 pos.y += acc->y;56 //pos.y += acc->y * 10; //调整精灵移动敏感度57 58 sprite->setPosition(pos);59 }