Phaser.Line.intersectsRectangle checks for intersection between a Line and a Rectangle, or any Rectangle-like object such as a Sprite or Body.

This commit is contained in:
photonstorm 2016-05-24 02:30:00 +01:00
parent c1c2e6bc9d
commit 07ef075e92
2 changed files with 93 additions and 1 deletions

View file

@ -336,7 +336,7 @@ You can read all about the philosophy behind Lazer [here](http://phaser.io/news/
### New Features
*
* Phaser.Line.intersectsRectangle checks for intersection between a Line and a Rectangle, or any Rectangle-like object such as a Sprite or Body.
*
*

View file

@ -627,6 +627,98 @@ Phaser.Line.intersects = function (a, b, asSegment, result) {
};
/**
* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like
* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body.
*
* An intersection is considered valid if:
*
* The line starts within, or ends within, the Rectangle.
* The line segment intersects one of the 4 rectangle edges.
*
* The for the purposes of this function rectangles are considered 'solid'.
*
* @method intersectsRectangle
* @param {Phaser.Line} line - The line to check for intersection with.
* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with.
* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle.
*/
Phaser.Line.intersectsRectangle = function (line, rect) {
// Quick bail out of the Line and Rect bounds don't intersect
if (!Phaser.Rectangle.intersects(line, rect))
{
return false;
}
var x1 = line.start.x;
var y1 = line.start.y;
var x2 = line.end.x;
var y2 = line.end.y;
var bx1 = rect.x;
var by1 = rect.y;
var bx2 = rect.right;
var by2 = rect.bottom;
var t = 0;
// If the start or end of the line is inside the rect then we assume
// collision, as rects are solid for our use-case.
if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) ||
(x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2))
{
return true;
}
if (x1 < bx1 && x2 >= bx1)
{
// Left edge
t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1);
if (t > by1 && t <= by2)
{
return true;
}
}
else if (x1 > bx2 && x2 <= bx2)
{
// Right edge
t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1);
if (t >= by1 && t <= by2)
{
return true;
}
}
if (y1 < by1 && y2 >= by1)
{
// Top edge
t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1);
if (t >= bx1 && t <= bx2)
{
return true;
}
}
else if (y1 > by2 && y2 <= by2)
{
// Bottom edge
t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1);
if (t >= bx1 && t <= bx2)
{
return true;
}
}
return false;
};
/**
* Returns the reflected angle between two lines.
* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2.