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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值