cocos2d-x中的重力感应还是比较简单的,先上代码
#define FIX_POS(_pos, _min, _max) \
if (_pos < _min) \
_pos = _min; \
else if (_pos > _max) \
_pos = _max; \
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = CCScene::create();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
// add layer as a child to scene
scene->addChild(layer);
} while (0);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
setAccelerometerEnabled(true);
m_pBall = CCSprite::create("ball.png");
m_pBall->setPosition(ccp(100, 150));
addChild(m_pBall);
m_pBall->retain();
bRet = true;
} while (0);
return bRet;
}
void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
{
CCDirector* pDir = CCDirector::sharedDirector();
CCSize size = pDir->getWinSize();
/*FIXME: Testing on the Nexus S sometimes m_pBall is NULL */
if ( m_pBall == NULL ) {
return;
}
CCSize ballSize = m_pBall->getContentSize();
CCPoint ptNow = m_pBall->getPosition();
CCPoint ptTemp = pDir->convertToUI(ptNow);
ptTemp.x += pAccelerationValue->x * 9.81f;
ptTemp.y -= pAccelerationValue->y * 9.81f;
CCPoint ptNext = pDir->convertToGL(ptTemp);
FIX_POS(ptNext.x, (0 + ballSize.width / 2.0), (size.width - ballSize.width / 2.0));
FIX_POS(ptNext.y, (0 + ballSize.height / 2.0), (size.height - ballSize.height / 2.0));
m_pBall->setPosition(ptNext);
}
setAccelerometerEnabled(true); 设置这一层重力感应启用
启用重力感应后,重力方向变化时,会回调CCLayer的方法didAccelerate( CCAcceleration* pAccelerationValue ),在自己派生的层里重写此方法
pAccelerationValue包含x,y,z三个方向的重力值(由手机在这3个方向的偏移决定)
如果觉得m_pBall->setPosition(ptNext);球移动不流畅,可以使用
CCMoveTo *moveTo = CCMoveTo::create(0.5f,pNext);
m_pBall->runAction(moveTo);