【cocos2d-x】重力感應----移動小球

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);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章