Game Development Reference
In-Depth Information
Time for action - adding our main loop
This is the heart of our game—the update method:
1. We will update the puck's velocity with a little friction applied to its vector
( 0.98f ). We will store what its next position will be at the end of the iteration, if
no collision occurred:
void GameLayer::update (float dt) {
auto ballNextPosition = _ball->getNextPosition();
auto ballVector = _ball->getVector();
ballVector *= 0.98f;
ballNextPosition.x += ballVector.x;
ballNextPosition.y += ballVector.y;
2. Next comes the collision. We will check collisions with each player sprite and the
ball:
float squared_radii = pow(_player1->radius() +
_ball->radius(), 2);
for (auto player : _players) {
auto playerNextPosition = player->getNextPosition();
auto playerVector = player->getVector();
float diffx = ballNextPosition.x -
player->getPositionX();
float diffy = ballNextPosition.y -
player->getPositionY();
float distance1 = pow(diffx, 2) + pow(diffy, 2);
float distance2 = pow(_ball->getPositionX() -
playerNextPosition.x, 2) + pow(_ball->getPositionY()
- playerNextPosition.y, 2);
Collisions are checked through the distance between ball and players. Two condi-
tions will flag a collision, as illustrated in the following diagram:
Search WWH ::




Custom Search