Game Development Reference
In-Depth Information
Now you can calculate the difference between the minimum allowed distance and the actual
distance, to get the intersection depth. If you look at the actual distance between the two centers,
there are two possibilities for both dimensions ( x and y ): the distance is either negative or positive.
For example, if the x distance is negative, this means rectangle rect is placed to the right of
rectangle this (because rect.center.x > this.center.x ). If rectangle this represents the character,
this means you have to move the characterto the left to correct this intersection. Therefore, you
return the x intersection depth as a negative value, which can be calculated as -minDistance.x -
distance.x . Why? Because there is a collision, the distance between the two rectangles is smaller
than minDistance . And because distance is negative, the expression -minDistance.x - distance.x
gives the difference between the two as a negative value. If distance is positive, the expression
minDistance.x - distance.x gives the positive difference between the two. The same reasoning
holds for the y distance. You can then calculate the depth as follows:
var depth = powerupjs.Vector2.zero;
if (distance.x > 0)
depth.x = minDistance.x - distance.x;
else
depth.x = -minDistance.x - distance.x;
if (distance.y > 0)
depth.y = minDistance.y - distance.y;
else
depth.y = -minDistance.y - distance.y;
Finally, you return the depth vector as the result of this method:
return depth;
When you know that the character collides with the tile, you calculate the intersection depth using
the method you just added to the Rectangle class:
var depth = boundingBox.calculateIntersectionDepth(tileBounds);
Now that you've calculated the intersection depth, there are two ways to solve this collision: move
the character in the x direction, or move the character in the y direction. Generally, you want to
move the character the least possible distance to avoid unnatural motions or displacements. So,
if the x depth is smaller than the y depth, you move the character in the x direction; otherwise you
move it in the y direction. You can check this with an if instruction. When comparing the two depth
dimensions, you have to take into account that they may be negative. You solve this by comparing
the absolute values:
if (Math.abs(depth.x) < Math.abs(depth.y)) {
// move character in the x direction
}
Do you always want to move the character if there is a collision with a tile? Well, that depends
on the tile type. Remember that TileType is used to represent three possible tile types:
TileType.background , TileType.normal , and TileType.platform . If the tile the character is colliding
with is a background tile, you definitely don't want to move the character. Also, in the case of moving
in the x direction, you want the character to be able to pass through platform tiles. Therefore, the
Search WWH ::




Custom Search