cocos2dx 3.x(让精灵随着重力感应的方向移动而移动)

时间:2023-09-19 15:45:56
 //
// GameScene.hpp
// HelloWord
//
// Created by apple on 2017/1/7.
//
// #ifndef GameScene_hpp
#define GameScene_hpp #include <stdio.h>
#include "cocos2d.h" USING_NS_CC; class GameScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene(); virtual bool init(); //重力感应回调函数
void didAccelerate(Acceleration* acc, Event* event); CREATE_FUNC(GameScene); private:
Size size;
Sprite *sprite;
};
#endif /* GameScene_hpp */
 //
// GameScene.cpp
// HelloWord
//
// Created by apple on 2017/1/7.
//
// #include "GameScene.hpp"
USING_NS_CC; cocos2d::Scene* GameScene::createScene()
{
auto scene = Scene::create(); //创建一个场景
auto layer = GameScene::create(); //创建一个图层
scene->addChild(layer);
return scene;
} //初始化当前的图层
bool GameScene::init()
{
if(!Layer::init()) //初始化父类
return false; //获取屏幕大小
size = Director::getInstance()->getVisibleSize();
//auto size = Director::getInstance()->getWinSize();
//添加一个图片精灵
sprite = Sprite::create("CloseNormal.png");
sprite->setPosition(Vec2(size.width/, size.height/));
sprite->setTag();
this->addChild(sprite); //开启重力感应
Device::setAccelerometerEnabled(true); //创建事件监听对象
auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(GameScene::didAccelerate, this)); //在事件监听器中注册
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true;
} void GameScene::didAccelerate(Acceleration* acc, Event* event)
{
//使精灵随重力感应移动
auto sprite = this->getChildByTag(); //通过标签获取精灵 auto pos = sprite->getPosition(); pos.x += acc->x;
pos.y += acc->y;
//pos.y += acc->y * 10; //调整精灵移动敏感度 sprite->setPosition(pos);
}