Reputation: 127
What's is the best way in Two.js to implement shape intersection? Currently trying with turf.js like this:
import { point, polygon } from '@turf/turf';
import pointInPolygon from '@turf/boolean-point-in-polygon';
// Shape and container here are both Two.Rectangle.
const contains = (shape, container) => {
const shapeVertices = shape.vertices.map((vertex) => {
const rotated = _rotatePoint({ x: 0, y: 0 }, shape.rotation, vertex);
return [rotated.x + shape.translation.x, rotated.y + shape.translation.y];
});
const containerVertices = container.vertices.map((vertex) => {
const rotated = _rotatePoint({ x: 0, y: 0 }, container.rotation, vertex);
return [
rotated.x + container.translation.x,
rotated.y + container.translation.y,
];
});
containerVertices.push(containerVertices[0]);
const _polygon = polygon([containerVertices]);
const points = shapeVertices.map((vertex) => point(vertex));
for (const point of points) {
if (!pointInPolygon(point, _polygon)) return false;
}
return true;
};
function _rotatePoint(center, angle, point) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const nx = cos * (point.x - center.x) - sin * (point.y - center.y) + center.x;
const ny = sin * (point.x - center.x) + cos * (point.y - center.y) + center.y;
return { x: nx, y: ny };
}
When the shapes are rotated it does not accurately detect.
The previous version, that did not support rotation and actually worked ok:
const cowntains = (shape, container) => {
const containerVertices = container.vertices.map((v) => [v.x, v.y]);
containerVertices.push(containerVertices[0]);
const _polygon = polygon([containerVertices]);
const points = shape.vertices.map((vertex) => point([vertex.x, vertex.y]));
const results = points.map((p) => pointInPolygon(p, _polygon));
return results.reduce((acc, curr) => acc && curr, true);
};
So before I keep working on this, is there a built-in way in Two.js? Or a better approach?
tia
Upvotes: 0
Views: 57