Game Development Reference
In-Depth Information
only case where you want to move the character to correct a collision is when it's colliding with a
wall tile ( TileType.normal ). In that case, you move the character by adding the x depth value to the
character position:
if (tileType === TileType.normal)
this.position.x += depth.x;
If you want to correct the character position in the y direction, things become slightly more complicated.
Because you're dealing with movement in the y direction, this is also a good place to determine
whether the character is on the ground. In the beginning of the handleCollisions method, you set the
isOnTheGround member variable to false . So, the starting point is to assume that the character is not
on the ground. In some cases, it's on the ground, and you have to set the variable to true . How can
you check if the character is on the ground? If it isn't on the ground, it must be falling. If it's falling,
then the previous y position is smaller than the current position. In order to have access to the previous
y position, you store it in a member variable at the end of each call to the handleCollisions method:
this._previousYPosition = this.position.y;
Now it's very easy to determine if the character is on the ground. If the previous y position was
smaller than the top of the tile the character is colliding with, and the tile is not a background tile,
then the character was falling and has reached a tile. If so, you set the isOnTheGround variable to
true and the y velocity to 0:
if (this._previousYPosition <= tileBounds.top && tileType !== TileType.background) {
this.onTheGround = true;
this.velocity.y = 0;
}
You still have to correct the character position in some cases. If you're colliding with a wall tile,
you always want to correct the character position. If the character is colliding with a platform tile,
you only want to correct the character position if it's standing on top of the tile. The latter is only
true if the isOnTheGround variable is set to true . Therefore, you can write all this in the following if
instruction:
if (tileType === TileType.normal || this.onTheGround)
this.position.y += depth.y + 1;
Note that to correct the position, you need to add one extra pixel to compensate for the extra pixel
you added to the bounding box's height.
What You Have Learned
In this chapter, you have learned:
How to constrain a character within the environment
How to simulate jumping and falling
How to deal with collisions in games
 
Search WWH ::




Custom Search