handling the intersection of two rectangles in a platformer
I am working on a simple platform game in HTML5/Canvas/Javascript/jQuery. You can see it here.
I'm aware of how to check the intersection of two rectangles (there are several questions on here regarding that), and my game checks and handles the intersection of the two rectangles, but only under very specific circumstances, and only because the character is not wider than my block.
My question: how do I calculate the intersection of two rectangles in a way which I can tell which direction the intersection occurs from? The only way I can think of includes 20+ if statements (this cannot be the proper way?).
I need to know the direction of intersection because I "peek" ahead to see if my sprite coordinates (x + dx, y开发者_StackOverflow社区 + dy) will intersect a rectangle, and if they will, set the sprite's new coordinates to just the edge of the rectangle on the next tick.
To get the position of a rectangle relatively to an other, you could use the center the sprite rectangle and get its position to the block.
The following function is to get position of a point to another. It should help you. Just need to adapt to verify the position of your sprite to your block using the center of the sprite and the center of the block (or verify the position of the sprite center to the top left and bottom right corners of the block)
function positionOf(point, relativeTo) {
var dx = point.x - relativeTo.x; // diff on x axis
var dy = point.y - relativeTo.y; // diff on y axis
if(dx >= dy) { // point is on top right half from relativeTo
return dx >= - dy ? 'EAST' : 'NORTH';
}
else { // point is on bottom left half from relativeTo
return dx >= - dy ? 'SOUTH' : 'WEST';
}
}
EDIT : all of this is good when considering x and y axis origin is at top left corner of viewport
精彩评论