Skip to content
Search

Cocos2dx:CCAcceleration

lastmod 2018-08-17created 2017-11-101 edits

Basic usage

First, override the methods for receiving the related events.

virtual void onEnter();
virtual void didAccelerate(cocos2d::CCAcceleration * acceleration);

In addition, onEnter() is described as follows.

  • Event callback that is invoked every time when CCNode enters the 'stage'.
  • If the CCNode enters the 'stage' with a transition, this event is called when the transition starts. During onEnter you can't access a "sister/brother" node. If you override onEnter, you shall call its parent's one, e.g., CCNode::onEnter().

Enable the accelerometer in onEnter().

void GameScene::onEnter()
{
    CCLayer::onEnter();
    setAccelerometerEnabled(true);
}

Write a macro that keeps the position from going off-screen when the sensor is applied.

#define FIX_POSITION(pos, min, max) \
    if (pos < min) { \
        pos = min; \
    } else if (pos > max) { \
        pos = max; \
    }

Create the player CCSprite character in init().

_player = CCSprite::create(kPlayerPng);
if (_player != NULL) {
    _player->setPosition(ccp(window_size.width / 2.0f, window_size.height / 2.0f));
    _player->retain();
    addChild(_player);
}

The important point is that the player object is kept as a member variable, and _player->release(); must be called in the destructor. Finally, implement didAccelerate().

void GameScene::didAccelerate(cocos2d::CCAcceleration * acceleration)
{
    using namespace cocos2d;

    CCDirector * director = CCDirector::sharedDirector();
    if (_player == NULL || director == NULL) {
        return;
    }

    CCSize player_size = _player->getContentSize();

    CCPoint player_position = _player->getPosition();
    CCPoint ui_position = director->convertToUI(player_position);

    ui_position.x += acceleration->x * kGravityConstant;
    ui_position.y -= acceleration->y * kGravityConstant;

    CCPoint next_position = director->convertToGL(ui_position);

    CCSize window_size = CCDirector::sharedDirector()->getWinSize();

    FIX_POSITION(next_position.x,
            (player_size.width  / 2.0f),
            (window_size.width  - player_size.width  / 2.0f));
    FIX_POSITION(next_position.y,
            (player_size.height / 2.0f),
            (window_size.height - player_size.height / 2.0f));

    _player->setPosition(next_position);
}

See also