Moving the player

We had called the scheduleUpdate function in the init function of the Player class. Thus, we define the update function to handle the movement and rotation of the player:

void Player::update(float dt)
{
  CCDrawNode::update(dt);
  CCPoint previous_position = m_obPosition;
  UpdatePosition();
  UpdateRotation(previous_position);
}

We first save the previous position of the player because we need it while setting the rotation. The UpdateRotation function will just use ccpToAngle function to set the rotation of the player with a bit of easing, so we will skip it and discuss only the UpdatePosition function as follows:

void Player::UpdatePosition()
{
  // don't move if speed is too low
  if(ccpLength(speed_) > 0.75f)
  {
    // add speed but limit movement within the boundary
    CCPoint next_position = ccpAdd(m_obPosition, speed_);
    if(RECT_CONTAINS_CIRCLE(game_world_->boundary_rect_, 
      next_position, PLAYER_RADIUS))
    {
      setPosition(next_position);
    }
    else
    {
      if(RECT_CONTAINS_CIRCLE(game_world_->boundary_rect_, CCPoint(
        next_position.x - speed_.x, next_position.y), PLAYER_RADIUS))
      {
        setPosition(ccp(next_position.x - speed_.x, next_position.y));
      }
      else if(RECT_CONTAINS_CIRCLE(game_world_->boundary_rect_, CCPoint(
        next_position.x, next_position.y - speed_.y), PLAYER_RADIUS))
      {
        setPosition(ccp(next_position.x, next_position.y - speed_.y));
      }
    }
  }
}

We ignore the values that are less than a certain threshold; otherwise, the player will constantly be jerking around the screen owing to the accelerometer readings constantly fluctuating by minor values. The logic is to calculate the next position by adding up the speed and finally limiting the player within the boundary defined by GameWorld.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.106