What is the method for determining if a point lies between two others?

I created a small function that seems to have a glitch...

function determineIfPointIsBetweenTwoOtherPoints (pointA, pointB, pointToCheck) {
    var vectorAB = new THREE.Vector3();
    vectorAB.subVectors(pointA, pointB).normalize();

    var vectorBA = new THREE.Vector3();
    vectorBA.subVectors(pointB, pointA).normalize();

    var vectorAPointToCheck = new THREE.Vector3();
    vectorAPointToCheck.subVectors(pointA, pointToCheck).normalize();

    var vectorBPointToCheck = new THREE.Vector3();
    vectorBPointToCheck.subVectors(pointB, pointToCheck).normalize();

    if(vectorAPointToCheck.dot(vectorAB) < 0 || vectorBPointToCheck.dot(vectorBA) < 0)
       return false;
    else 
       return true;
}

https://i.sstatic.net/8fWBG.png What's going wrong? My function output indicates that the left point is between the two on the right

@Pete The revised function is:

function checkIfPointLiesBetweenTwoOthers (pointA, pointB, pointToCheck) {
    var vectorAB = new THREE.Vector3();
    vectorAB.subVectors(pointA, pointB);
    var lengthAB = vectorAB.length();

    var vectorBA = new THREE.Vector3();
    vectorBA.subVectors(pointB, pointA);
    var lengthBA = vectorBA.length();

    var vectorAPointToCheck = new THREE.Vector3();
    vectorAPointToCheck.subVectors(pointA, pointToCheck);

    var vectorBPointToCheck = new THREE.Vector3();
    vectorBPointToCheck.subVectors(pointB, pointToCheck);

    var vectorToPointA = new THREE.Vector3();
    vectorToPointA.subVectors(pointToCheck, pointA);
    var lengthToPointA = vectorToPointA.length();

    if(lengthToPointA > lengthBA) {
        return false;
    } else if(vectorToPointA.dot(vectorBA) > 0.999999 * vectorToPointA.x * vectorBA.x + vectorToPointA.y * vectorBA.y + vectorToPointA.z * vectorBA.z) {
        return true;
    } else {
        return false;
    }
}

Now (the dark sphere in the image below represents point C), it returns true for this case only when I add the 0.999999 value. Otherwise, it works accurately for this scenario... https://i.sstatic.net/JtwVW.png However, in another situation without 0.9999, it indicates that point C is not between points A & B with these coordinates...

var t1 = new THREE.Vector3(1,1,1); //A
var t2 = new THREE.Vector3(-1,1,1); //B
var t3 = new THREE.Vector3(-0.3999999999999999,1,1);  //C

https://i.sstatic.net/5w275.png

Answer №1

In order to determine if point C is positioned between points A and B, one can calculate the vector differences by subtracting point A from point B (u=subVectors(pB,pA)) and point A from point C (v=subVectors(pC,pA)). Then, find the lengths of both vectors lu and lv. If lv>lu, it indicates that point C is farther away from point A than point B. Conversely, if this condition is not met, check if the dot product of vectors u and v is equal to lu*lv (or potentially higher than 0.9999*lu*lv with some numerical tolerance). Return true if these conditions are satisfied, otherwise return false. Essentially, if point C is not farther from point A than point B, and the vectors from A to B and from A to C are parallel (but not anti-parallel), then the dot product equals lu*lv, indicating that point C lies between points A and B.

Answer №2

If you need to determine the vector from point pA to point pB, it is important to subtract pA from pB (pB-pA) rather than vice versa (pA-pB).
Please note that the method

.subVectors( a : Vector3, b : Vector3 )
calculates a-b.


In brief:

To confirm if the distance between pA and pToCheck, as well as between pB and pToCheck, is less than or equal to the distance between pA and pB, follow these steps:
- Check the angle between vectors connecting pA to pToCheck and pB to pToCheck, compared to the vector from pA to pB. Utilize methods like .distanceTo and .angleTo for this purpose:

function isPointbetweenTwoOthers (pointA, pointB, checkPoint) {

    let distAtoB = pointA.distanceTo(pointB);
    let distAtoC = pointA.distanceTo(checkPoint);
    let distBtoC = pointB.distanceTo(checkPoint);
    
    // Perform necessary checks and return true or false accordingly
}

Detailed explanation:

The Dot product of two vectors A and B equals the product of their magnitudes times the cosine of the angle between them.

If both vectors are normalized (unit vectors), the dot product corresponds to the cosine of the angle itself:
For unit vectors uA and uB:
Vectors in diagram:

uA = normalize(A)
uB = normalize(B)
uA dot uB == cos(alpha)

The cosine value signifies the angle's orientation, with positive values indicating an angle within -90° to 90° range. The angle is 0° at cosine 1.0, and 180° at cosine -1.0.

In cases where you wish to verify if pC lies on the line segment from pA to pB, ensure that the angle between involved vectors mimics a straight line (~0°). Due to computation precision limitations, consider a near-1.0 epsilon margin while dealing with normalized vectors:

Function logic covering detailed calculations here...

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

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

Combining DataTables with multiple tables sourced from various JSON arrays

I am trying to display data from two different arrays within the same JSON source in two separate tables, but my code seems to be malfunctioning. JSON Information: { "Policies": [ { "name": "A", "id": "1", "score": "0" } ], ...

Troubleshooting a Form Validation Issue with React's useState Hook

I am currently working on form validation for a project. The form includes two essential elements: a textbox for messages and a textbox for recipients. These elements are controlled by state.message (a string) and state.recipients (an array). The state var ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

What are the advantages of generating an HTML string on the server side and adding it to the client side?

Is there a more efficient method for transferring a large amount of data from the server to the client and dynamically generating tables, divs, and other HTML elements using JavaScript (jQuery)? Initially, I attempted to generate these elements on the cli ...

Tips for launching a fresh window and embedding HTML into it with jQuery?

I'm attempting to use JavaScript to open a new window, but the HTML content is not being added: var callScriptText = $('#callScriptText').html(); var url = '/Action/CallScript/?callScript='; // Open the current call script in a n ...

Guidance on exporting an Excel file from an HTML table, excluding the final row, using JavaScript

I'm able to export an Excel file from an HTML table, but I'm facing an issue where the last row (tr) meant for pagination on the screen is also being included in the exported result. How can I exclude this row from showing up in the Excel file? ...

What steps should I take to modify the URL using the SELECT tag?

Having a bunch of SELECT tags in place <select id="url"> <option id="url1" >url 1</option> <option id="url2" >url 2</option> </select> <button onclick="go()">GO</button> Followed by the associated scrip ...

Error encountered: Loader fails to display during AJAX request

Currently, I am facing an issue with a JavaScript function that triggers an AJAX call to fetch some data when there is a change in a select list event. I have experimented with various methods to display a loader while the data is being fetched, as the cu ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...

Generating an image in Fabric.js on a Node server following the retrieval of canvas data from a JSON

I've been trying to solve this problem for the past few days. In my app, users can upload two images, with one overlaying the other. Once they position the images and click a button, the canvas is converted to JSON format and sent to a node (express) ...

error message: "The CSRF token is either missing or incorrect, please try again."

I implemented window.CSRF_TOKEN = "{{ csrf_token }}" within a script tag in restaurant_detail.html where my react page for posting reviews is rendered. However, I encountered an error. Upon checking in my onSubmit function, I confirmed that the csrf token ...

Issues arise with the functionality of CSS and JavaScript after successfully deploying a Next.js and React project to the server side

I need to deploy my React+Next and Node.js projects on the same port. To achieve this, I converted my TypeScript files to JavaScript and moved the .next folder to the backend side. Now, my API and frontend code are functioning on the same port thanks to Ex ...

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

Retrieve the currently displayed page on a bootstrap table

I'm currently utilizing the bootstrap table to showcase my data. One of the features I have added is a column with an edit button for each row. Upon clicking on the edit button, I open a bootstrap modal that displays the data from the corresponding ro ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

"An issue was encountered in the original callback" while utilizing ffi-napi within electron and electron-builder

I am encountering a challenge with my electron app. I am attempting to use ffi-napi to call a dll file, but when I run the electron build, I encounter an "Error in native callback." Here is the setup I am working with: package.json { "name": & ...

Tips for implementing next-iron-session with personalized api route middleware in NextJS?

Currently, I am working on implementing session storage with next-iron-session and using Firebase for authentication. Every API route requires both the auth middleware and next-iron-session. This is my first time using NextJS and I have tried several appro ...