arcade-physics
Version:
Use Arcade Physics without Phaser.
62 lines • 2.29 kB
JavaScript
;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Contains_1 = __importDefault(require("../circle/Contains"));
const Point_1 = __importDefault(require("../point/Point"));
const tmp = new Point_1.default();
/**
* Checks for intersection between the line segment and circle.
*
* Based on code by [Matt DesLauriers](https://github.com/mattdesl/line-circle-collision/blob/master/LICENSE.md).
*
* @function Phaser.Geom.Intersects.LineToCircle
* @since 3.0.0
*
* @param {Phaser.Geom.Line} line - The line segment to check.
* @param {Phaser.Geom.Circle} circle - The circle to check against the line.
* @param {(Phaser.Geom.Point|any)} [nearest] - An optional Point-like object. If given the closest point on the Line where the circle intersects will be stored in this object.
*
* @return {boolean} `true` if the two objects intersect, otherwise `false`.
*/
const LineToCircle = (line, circle, nearest) => {
if (nearest === undefined) {
nearest = tmp;
}
if ((0, Contains_1.default)(circle, line.x1, line.y1)) {
nearest.x = line.x1;
nearest.y = line.y1;
return true;
}
if ((0, Contains_1.default)(circle, line.x2, line.y2)) {
nearest.x = line.x2;
nearest.y = line.y2;
return true;
}
const dx = line.x2 - line.x1;
const dy = line.y2 - line.y1;
const lcx = circle.x - line.x1;
const lcy = circle.y - line.y1;
// project lc onto d, resulting in vector p
const dLen2 = dx * dx + dy * dy;
let px = dx;
let py = dy;
if (dLen2 > 0) {
const dp = (lcx * dx + lcy * dy) / dLen2;
px *= dp;
py *= dp;
}
nearest.x = line.x1 + px;
nearest.y = line.y1 + py;
// len2 of p
const pLen2 = px * px + py * py;
return pLen2 <= dLen2 && px * dx + py * dy >= 0 && (0, Contains_1.default)(circle, nearest.x, nearest.y);
};
exports.default = LineToCircle;
//# sourceMappingURL=LineToCircle.js.map