一、开始学cocos2d-x没多久,其实也就是根据官方事例写的一个小Demo,直接写代码:
二、代码段
AccelerometerTest.h
#include "cocos2d.h"
USING_NS_CC;
class AccelerometerTest:public Layer
{
public:
static Scene* createScene();
virtual bool init();
void onAcceleration(Acceleration* acc, Event* event);
CREATE_FUNC(AccelerometerTest);
Sprite* m_ball;
};
AccelerometerTest.cpp
#include "AccelerometerTest.h"
#define FIX_POS(_pos, _min, _max) \
if (_pos < _min) \
_pos = _min; \
else if (_pos > _max) \
_pos = _max;
Scene* AccelerometerTest::createScene()
{
auto scene = Scene::create();
auto layer = AccelerometerTest::create();
scene->addChild(layer);
return scene;
}
bool AccelerometerTest::init()
{
if(!Layer::init())
{
return false;
}
setAccelerometerEnabled(true);
auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
Size visibleSize = Director::getInstance()->getVisibleSize();
auto label = Label::createWithTTF("AccelerometerTest", "fonts/Marker Felt.ttf", 32.0f);
label->setPosition(Vec2(visibleSize.width/2,visibleSize.height-50));
this->addChild(label);
m_ball=Sprite::create("ball.png");
m_ball->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));
this->addChild(m_ball);
return true;
}
void AccelerometerTest::onAcceleration(Acceleration* acc, Event* event)
{
if(m_ball==nullptr)
{
return;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
auto ballSize=m_ball->getContentSize();
auto pos=m_ball->getPosition();
pos.x += acc->x * 9.81f;
pos.y += acc->y * 9.81f;
FIX_POS(pos.x,(ballSize.width/2),(visibleSize.width-ballSize.width/2));
FIX_POS(pos.y,(ballSize.height/2),(visibleSize.height-ballSize.height/2));
m_ball->setPosition(pos);
}
三、遇到问题
1、 Sprite* m_ball; // 已经在头文件中定义,又在 init() 方法中 写为 auto m_ball ,导致 m_ball==nullptr
2、 auto label = Label::createWithTTF("AccelerometerTest", "fonts/Marker Felt.ttf", 32.0f);
// 此处字体名称写为小写,移植到Android中报错,应保持与字体文件名称大小写一致
一些不起眼的小问题花费很多时间,脑残了