这次这个只是我学习的一个记录,重力感应就像touch事件一样,我们在init里面开启重力感应事件,然后重写函数就可以了。
首先在init里面开启重力事件:
this->setAccelerometerEnabled(true);//开启重力感应
this->setKeypadEnabled(true);//这个是开启手机的返回键事件,大家可以忽略这个
现在我们重写函数:
//重力感应事件
virtual void didAccelerate(CCAcceleration* pAccelerationValue);
//返回按钮,大家可以忽略
virtual void keyBackClicked();
相应函数的重写:
屏幕的宏:
#define FIX_POS(_pos, _min, _max) \
if (_pos < _min) \
_pos = _min; \
else if (_pos > _max) \
_pos = _max;
bool HelloWorld::init()
{
//
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
CCLabelTTF *lable= CCLabelTTF::create("HelloWorld","Arial",34);
lable->setPosition(ccp(visibleSize.width/2,visibleSize.height-50));
this->addChild(lable,0,0);
CCSprite *pSprite= CCSprite::create("CloseNormal.png");
pSprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
this->addChild(pSprite,0,1);
this->setAccelerometerEnabled(true);//开启重力感应
this->setKeypadEnabled(true);
return true;
}
void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
{
CCObject *pObjectlable= this->getChildByTag(0);
if (pObjectlable==NULL)
{
return;
}
CCLabelTTF *lable=(CCLabelTTF*)pObjectlable;
std::ostringstream strstream;//输出相应的x,y,z
strstream<<"X:"<<pAccelerationValue->x<<" Y:"<<pAccelerationValue->y<<" Z:"<<pAccelerationValue->z;
std::string str=strstream.str();
lable->setString(str.c_str());
//改变小球位置
CCObject *pObjectSprite= this->getChildByTag(1);
if (pObjectSprite==NULL)
{
return;
}
CCSprite *pSprite=(CCSprite*)pObjectSprite;
CCSize pSpriteSize= pSprite->getContentSize();
CCPoint ptNow = pSprite->getPosition();
CCPoint ptTemp=CCDirector::sharedDirector()->convertToUI(ptNow);
ptTemp.x += pAccelerationValue->x * 9.81f;
ptTemp.y -= pAccelerationValue->y * 9.81f;
CCPoint ptNext = CCDirector::sharedDirector()->convertToGL(ptTemp);
CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
FIX_POS(ptNext.x, (pSpriteSize.width / 2.0), (visibleSize.width - pSpriteSize.width / 2.0));
FIX_POS(ptNext.y, (pSpriteSize.height / 2.0), (visibleSize.height - pSpriteSize.height / 2.0));
pSprite->setPosition(ptNext);
}
void HelloWorld::keyBackClicked()//可以忽略
{
}
我们的功能主要是创建了一个小球,然后发布在手机上就可以看见相应的效果。
大家轻喷
----------蛋蛋