Game Development Reference
In-Depth Information
We don't check the collision if
_player
is dying and we skip collision checks
with any gap blocks.
We check collision on the
y
axis, which here means the bottom of the
_player
and top of the block. We first need to determine if the
_player
object is within
range of the block we want to check against collision. This means the center of
the
_player
object must be between the left and right side of the block; other-
wise, the block is too far from the
_player
object and may be ignored.
Then we run a basic check to see if there is a collision between the
_player
ob-
ject's current position and next position, using the conditions I explained earlier. If
so, we fix the
_player
object's position and change its
y
vector speed to
0
and
we determine that
inAir = false
after all, the
_player
object has landed.
2. Next we check collision on the
x
axis, meaning the right side of the
_player
object with the left side of the blocks:
for (auto block : _blocks) {
if (block->getType() == kBlockGap) continue;
//now if within y, check x (side collision)
if ((player->bottom() < block->top() &&
player->top() > block->bottom()) ||
(player->next_bottom() < block->top() &&
player->next_top() > block->bottom())) {
if (player->right() >= this->getPositionX() +
block->getPositionX() && player->left() <
this->getPositionX() + block->getPositionX()) {
player->setPositionX( this->getPositionX() +
block->getPositionX() - player->getWidth() * 0.5f );
player->setNextPosition(Vec2(this->getPositionX() +
block->getPositionX() - player->getWidth() * 0.5f,
player->getNextPosition().y));
player->setVector ( Vec2(player->getVector().x
* -0.5f, player->getVector().y) );
if (player->bottom() + player->getHeight() *
0.2f < block->top()) {
player->setState(kPlayerDying);
return;
}