Reputation: 111
How to detect a THREE.Line whether lies on between THREE.Line's start and end points or not in ThreeJS ?
I have tried folling code:
function checkLineOverlap (start1: Point, end1: Point, start2: Point, end2: Point): boolean {
const denominator = ((end2.z - start2.z) * (end1.x - start1.x)) - ((end2.x - start2.x) * (end1.z - start1.z));
// Check if the lines are parallel or coincident
if (denominator === 0) {
return false;
}
const ua = (((end2.x - start2.x) * (start1.z - start2.z)) - ((end2.z - start2.z) * (start1.x - start2.x))) / denominator;
const ub = (((end1.x - start1.x) * (start1.z - start2.z)) - ((end1.z - start1.z) * (start1.x - start2.x))) / denominator;
// Check if the intersection point lies within both line segments
const isInsideLine1 = (ua >= 0 && ua <= 1);
const isInsideLine2 = (ub >= 0 && ub <= 1);
// Return true if both lines intersect within the line segments
return isInsideLine1 && isInsideLine2;
}
const line1Start = new THREE.Vector3(0, 0, 0);
const line1End = new THREE.Vector3(10, 0, 0);
const line2Start = new THREE.Vector3(8, 0, 0);
const line2End = new THREE.Vector3(5, 0, 5);
// Check for line overlap
const isOverlap = checkLineOverlap(line1Start, line1End, line2Start, line2End);
// Check the result
if (isOverlap) {
console.log('The lines overlap.');
} else {
console.log('The lines do not overlap.');
}
This code is not working properly. isOverlap function returns true when the lines across to each other. But in my case, the function should return true when the line1 lies on between line2's start and end points.
Hope following image shows what I meant:
Upvotes: 0
Views: 90
Reputation: 61
Please try this
function checkSegmentsOverlap(startA, endA, startB, endB) {
var minX = Math.min(startA.x, endA.x);
var maxX = Math.max(startA.x, endA.x);
var minY = Math.min(startA.y, endA.y);
var maxY = Math.max(startA.y, endA.y);
var minZ = Math.min(startA.z, endA.z);
var maxZ = Math.max(startA.z, endA.z);
return (
startB.x >= minX && startB.x <= maxX &&
endB.x >= minX && endB.x <= maxX &&
startB.y >= minY && startB.y <= maxY &&
endB.y >= minY && endB.y <= maxY &&
startB.z >= minZ && startB.z <= maxZ &&
endB.z >= minZ && endB.z <= maxZ
);
}
// Check for line overlap
const isOverlap = checkSegmentsOverlap(line1Start, line1End, line2Start, line2End) | checkSegmentsOverlap(line2Start, line2End, line1Start, line1End);
// Check the result
if (isOverlap) {
console.log('The lines overlap.');
} else {
console.log('The lines do not overlap.');
}
Upvotes: 1