How can Three.js help you identify whether a point lies on a given line?

Is there a way to determine if a specific point (x,y,z) lies on the line segment between two other points, pointA and pointB?

I am looking for a boolean function that can efficiently solve this problem:

pointA        // random THREE.Vector3
pointB        // random THREE.Vector3
pointToCheck  // random THREE.Vector3
var isOnLine = THREE.pointOnLine(pointA, pointB, pointToCheck)

if (isOnLine) {
  console.log('point is on the line');
}

Please refer to the image below for better understanding:

https://i.sstatic.net/LmStm.gif

Answer №1

Utilizing the cross product operation of two vectors can provide a solution to this particular problem.

function verifyPointAlignment (point1, point2, pointToVerify) {
    var check = new THREE.Vector3();   
    check.crossVectors(point1.clone().sub(pointToVerify), point2.clone().sub(pointToVerify));
    return !check.length();
}

THREE.verifyPointOnLineAndBetweenPoints = function (point1, point2, pointToVerify) {
    if (!verifyPointAlignment(point1, point2, pointToVerify)) {
        return false;
    }

    var dx = point2.x - point1.x;
    var dy = point2.y - point1.y;

    // determining if the line is more horizontal or vertical:
    if (Math.abs(dx) >= Math.abs(dy)) {
        if (dx > 0) {
            return point1.x <= pointToVerify.x && pointToVerify.x <= point2.x;
        } else {
            return point2.x <= pointToVerify.x && pointToVerify.x <= point1.x;
        }
    } else {
        if (dy > 0 ) {
            return point1.y <= pointToVerify.y && pointToVerify.y <= point2.y;
        } else {
            return point2.y <= pointToVerify.y && pointToVerify.y <= point1.y;
        }
    }
}

A sample call:

THREE.verifyPointOnLineAndBetweenPoints(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));

If you only need to determine if a point lies on a line, use the following function:

verifyPointAlignment(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));

Answer №2

This is a much simpler approach.

function checkIfPointIsOnLine (pointA, pointB, targetPoint) {
    var vectorC = new THREE.Vector3();   
    vectorC.crossVectors(pointA.clone().sub(targetPoint), pointB.clone().sub(targetPoint));
    return !vectorC.length(); }

THREE.checkIfPointIsOnLineAndBetweenPoints = function (pointA, pointB, targetPoint) {
    if (!checkIfPointIsOnLine(pointA, pointB, targetPoint)) {
        return false;
    }

    let distanceAB = pointA.distanceTo(pointB);

    return pointA.distanceTo(targetPoint) < distanceAB && pointB.distanceTo(targetPoint) < distanceAB;
}

Answer №3

To determine if a point lies on a three-dimensional line, you can convert the equation into symmetric form and evaluate using the given points. Here's an example code snippet for reference:

// Select two random points to define the line
var pointA = new THREE.Vector3(-70, -4, -100);
var pointB = new THREE.Vector3(65, 22, 14);

// Function to check if pointToCheck lies on the line defined by pointA and pointB
var isOnLine = function(pointA, pointB, pointToCheck, betweenCheck) {
    // Calculating directional vectors
    xVector = pointB.x - pointA.x;
    yVector = pointB.y - pointA.y;
    zVector = pointB.z - pointA.z;
    vector = [xVector, yVector, zVector];

    // Additional check for points lying between pointA and pointB
    if (!!betweenCheck) {
        // Implement logic to validate between condition
    }

    // Convert to symmetric form for evaluation
    var x = (pointToCheck.x - pointA.x) / xVector;
    var y = (pointToCheck.y - pointA.y) / yVector;
    var z = (pointToCheck.z - pointA.z) / zVector;
    var results = [x, y, z];
    
    // Further processing to handle irrelevant coordinates

    return true; // Return result after evaluating symmetric equations
}

Here are some test scenarios:

// Generate multiple test points for validation
pointsOnLine = [];
pointsOffLine = [];
pointsOnLineBetween = [];
pointsOffLineBetween = [];

// Populate test arrays with generated points for various conditions

// Perform tests using the isOnLine function for each point category
for (var i = 0; i < pointsOnLine.length; i++) {
    // Execute test cases and log results
}

// Repeat above process for other point categories

Explore the Plunkr for live demonstration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating UV coordinates in THREE.js

I've been working on bringing a model into a scene using the OBJ loader in THREE.js. Initially, I had no issues importing the geometry and visualizing it with MeshNormalMaterial. However, as soon as I tried to use textures that require UV coordinates ...

Issue: Unauthorized access: nodeMailer despite correct configuration

Having trouble with an error when using the less app option on Gmail. I don't have 2-factor authentication enabled, and my credentials are correct. I can log in to my file to verify this, but the error still persists. const nodemailer = require(" ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

How to create a Bootstrap panel that collapses on mobile devices and expands on desktop screens?

Is there a simple way to remove the "in" class from the div with id "panel-login" when the screen size is less than 1199px (Bootstrap's xs, sm, and md modes)? I believe JavaScript or JQuery could be used for this, but I'm not very proficient in e ...

Is it possible to verify the user's authentication by confirming the presence of a JWT in their localStorage?

I am currently working on a project that requires JWT authentication. I have set up a registration form and login page where users receive an authorityToken and it is saved in localStorage. Once the user logs into their account : ` $("#btnLogin").click( ...

Utilizing Selenium to locate an element by its class name and then deleting it from the document object model through

I have found a code that worked really well for me. It involves getting the quantity of messages first and then removing them from the DOM. public static void RemoveMessages() { // Removing messages from the DOM using JavaScript ...

sophisticated HTML navigation bar

I am looking for a way to create a menu where the drop-down items overlay the rest of the menu when the screen width is small. Here is my current code: nav{ line-height:100%; opacity:.9; }nav ul{ background: #999; padding: 0px; border-radius: 20px; ...

Setting a specific time for a div element with opacity: A step-by-step guide

Is there a way to adjust the timing for the appearance of the add-to-cart when hovering over the product-list-item? Currently, it appears when I hover over the item and disappears when I move my mouse away. .product-list-item { position: relative; w ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

Creating combinations of strings using for loops -R

I'm exploring a simple concept of pairing strings using for loops. My goal is to create a function that generates all possible combinations of two characters. I have a general idea of how to accomplish this, but I'm struggling to make the output ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Explore the capabilities of redux independent of the react framework

I've been searching for hours trying to find a way to access the store (to dispatch and observe) without using React Components, but have had no luck. Here's my situation. I created the store in the root of the App: import { Provider } from &ap ...

Has the user successfully authenticated with Google?

Possible Repetition: How to verify if a user is logged into their Google account using API? I'm working on a website that displays a Google Calendar. My query is: Can I determine whether a user is currently logged into a Google Account? If it&ap ...

Exploring Checkbox Handling in AngularJS and ng-Grid

In my AngularJS application, I am using ng-grid to display data retrieved from a server. One of the fields, "Active," is boolean and I have created a template to show it as a checkbox: $scope.gridOptions = { data: 'myData', enableCellSelection: ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...

What could be causing this code to fail in making changes to the HTML document?

I tried incorporating the following code into my website: $('.feed-item').append('<p> This is paragraph element. </p>'); You can view it on this page: Test Unfortunately, the code does not seem to be functioning properly. ...

Save a CSV file into a list, locate a specific key within the list, and retrieve the fourth value associated with that key

After thorough revision, the question now reads as follows: Take a look at this content in database.csv: barcode,ScQty, Name , Qty ,Code 123456 , 3 ,Rothmans Blue , 40 ,RB44 234567 , 2 ,Rothmans Red , 40 ,RB30 345678 , 2 ,Rothmans Gre ...

Navigating to different HTML pages using JavaScript

Currently, I am working on transitioning from my login.html to account.html using JavaScript. In the login.html file, there will be a validation process using MongoDB. If the data matches, it should redirect to account.html; however, this is not happening ...