From b3b495e53cf38a90e33c1bb5cbc07fe52502aa25 Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Wed, 29 Mar 2017 15:05:29 +0100 Subject: [PATCH] Added Rectangle.PerimeterPoint method for getting the point on the perimeter of a rectangle based on the given angle. --- v3/src/geom/rectangle/PerimeterPoint.js | 66 +++++++++++++++++++++++++ v3/src/geom/rectangle/index.js | 1 + 2 files changed, 67 insertions(+) create mode 100644 v3/src/geom/rectangle/PerimeterPoint.js diff --git a/v3/src/geom/rectangle/PerimeterPoint.js b/v3/src/geom/rectangle/PerimeterPoint.js new file mode 100644 index 000000000..b9a3ad6a7 --- /dev/null +++ b/v3/src/geom/rectangle/PerimeterPoint.js @@ -0,0 +1,66 @@ +var MATH_CONST = require('../../math/const'); + +// deg = degrees + +var PerimeterPoint = function (rect, deg, out) +{ + if (out === undefined) { out = { x: 0, y: 0 }; } + + var theta = deg * MATH_CONST.DEG_TO_RAD; + + while (theta < -Math.PI) + { + theta += MATH_CONST.PI2; + } + + while (theta > Math.PI) + { + theta -= MATH_CONST.PI2; + } + + var rectAtan = Math.atan2(rect.height, rect.width); + var tanTheta = Math.tan(theta); + var thetaBounds = Math.PI - rectAtan; + var region; + var xFactor = 1; + var yFactor = 1; + + if (theta > -rectAtan && theta <= rectAtan) + { + region = 1; + yFactor = -1; + } + else if (theta > rectAtan && theta <= thetaBounds) + { + region = 2; + yFactor = -1; + } + else if (theta > thetaBounds || theta <= -thetaBounds) + { + region = 3; + xFactor = -1; + } + else + { + region = 4; + xFactor = -1; + } + + out.x = rect.x + (rect.width / 2); + out.y = rect.y + (rect.height / 2); + + if (region === 1 || region === 3) + { + out.x += xFactor * (rect.width / 2); // "Z0" + out.y += yFactor * (rect.width / 2) * tanTheta; + } + else + { + out.x += xFactor * (rect.height / (2 * tanTheta)); // "Z1" + out.y += yFactor * (rect.height / 2); + } + + return out; +}; + +module.exports = PerimeterPoint; diff --git a/v3/src/geom/rectangle/index.js b/v3/src/geom/rectangle/index.js index 6800bc8bd..12c0ddcbc 100644 --- a/v3/src/geom/rectangle/index.js +++ b/v3/src/geom/rectangle/index.js @@ -27,6 +27,7 @@ Rectangle.Offset = require('./Offset'); Rectangle.OffsetPoint = require('./OffsetPoint'); Rectangle.Overlaps = require('./Overlaps'); Rectangle.Perimeter = require('./Perimeter'); +Rectangle.PerimeterPoint = require('./PerimeterPoint'); Rectangle.Random = require('./Random'); Rectangle.Scale = require('./Scale'); Rectangle.Union = require('./Union');