Challenges arise when attempting to pinpoint distinct coordinates from within a spherical structure

I've recently started working with Three.js [r78] and I'm still a beginner in both Three.js and JavaScript in general.

After some trial and error, I was able to cast a ray from a perspective camera at the center of a sphere with a radius of 500. The intersection results seemed promising but not completely satisfying. I'm looking to accurately determine the coordinates of a point, whether cartesian or spherical. When selecting a specific point, I noticed that the cartesian coordinates vary. Sometimes they are close, sometimes quite different. Issues arise with zoom (mousewheel) as well as without changing it, as shown in the example image below where I added a white marker to indicate the selected point. The actual clicked point is inside the red circle.

https://i.sstatic.net/HAmhT.jpg

The same point is viewed from different angles with the same zoom level. I expected these two attempts to yield similar values. However, I confirmed that the distance from the camera to the intersection point is always around 500 units. This indicates that the collision point is calculated accurately.

Here are my two questions along with the core code snippet derived from Valiant360:

  • Is it a bug in this release of Three.js that the same physical point clicked with the mouse yields different coordinates? Or am I missing something/making mistakes?
  • If it's an error on my end, how can I rectify it to ensure consistent values even when changing the zoom level?

Thank you in advance for any assistance provided.
Antonino


    onMouseDown: function(a) 
    {
    [...]

    // retrieving normalized coordinates
    var mouse_2D_vector = new THREE.Vector2( ( event.clientX / window.innerWidth ) * 2 - 1,
                                    -( event.clientY / window.innerHeight ) * 2 + 1);        

    this._raycaster.setFromCamera(mouse_2D_vector, this._camera);

    var intersections = this._raycaster.intersectObjects( [this._mesh], true );
    intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null;

    if (intersections.length>0)
    {
        intersections[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );

        console.log("Intersected object.x:", intersections[ 0 ].point.x);
        console.log("Intersected object.y:", intersections[ 0 ].point.y);
        console.log("Intersected object.z:", intersections[ 0 ].point.z);
    }

    console.log('intersections.length: ' + intersections.length);       

    },

Answer №1

One drawback of raycasting is:

If the dimensions of the scene are not exactly window.innerWidth x window.innerHeight, calculating the location of a "mouse click" on the screen may be inaccurate due to incorrect scaling. This issue is not a flaw in Three.js, but rather stems from individuals using the same code repeatedly for raycasting without recognizing the need for scale adjustments.

To address this issue, you can either manually set the width and height values instead of relying on window.innerWidth/window.innerHeight,

or utilize JQuery $elements

Answer №2

It seems like you're struggling to pinpoint your exact question. Could you please summarize in bold what you would like to know?

From what I gather, you're wondering why the distance to the intersection is not consistently 500 units. The reason for this discrepancy lies in the nature of generated geometries. Unlike a perfectly round shape, which would yield a constant distance from center to perimeter, our geometry consists of interconnected triangles, as illustrated here:

https://i.sstatic.net/qcZaH.png

Within these triangles, the distance from center varies; it may approximate 500 at intersections but will decrease towards triangle centers. This phenomenon intensifies with simpler shapes.

This interpretation addresses your query, but feel free to refine your question if I have misunderstood any aspect, as your initial inquiry lacks clarity.

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

What is the reason that in jsxgraph, a parabola is not able to be created by connecting five points on a single plane?

I recently encountered an issue while working on a project involving drawing points in 3D space that move according to slider values. Even though the points moved correctly, I faced difficulty in drawing a conic section (specifically a parabola) through th ...

What is the correct way to embed a script tag within a block of JavaScript code?

I'm currently working on a JavaScript code that needs to be executed inside an iframe. The goal is to insert a script tag within the JavaScript code and then append it to the parent body of the iframe. Below is the snippet of my code attempting to ach ...

Tips for retrieving a value returned by a Google Maps Geocoder

geocoder.geocode( { 'address': full_address}, function(results, status) { lat = results[0].geometry.location.lat(); lng = results[0].geometry.location.lng(); alert(lat); // displays the latitude value correctly }); alert(lat); // does ...

Navigating routes with regular expressions in Express

Recently, I've implemented the regex pattern /^\/(\d{5})$/ in my express route. However, an error has surfaced. The error message reads: SyntaxError: Invalid regular expression: /^\/^\/(?(?:([^\/]+?)){5})$\/?$/: Inval ...

Responsive text area with Django and Bootstrap

I created a small JavaScript script to ensure that a text area adjusts responsively based on the size of the accompanying image. It generally works well, but there is a strange random bug that I can't quite figure out. This is how the page should be d ...

"Triggering an event after selecting and opening a file with an input of type file

Check out this snippet of HTML code: <input type="file" id="mysignature_upload" onChange="readURL();"/> We also have some Javascript code: function readURL(){ alert("Hello"); } A potential issue with this code is that the function readURL is on ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Using ng-repeat to iterate over an array of strings in Javascript

I am working with a JavaScript Array that contains strings: for(var i =0; i<db.length; i++) console.log(db[i]); When I run the code, the output is as follows: dbName:rf,dbStatus:true dbName:rt,dbStatus:false Now, I am trying to use ng-repeat to ...

Sending a POST request from a React child component to an Express server

I recently started working on a project using the MERN stack, incorporating react-router and redux. Within my application, I have integrated a <Navbar /> component along with a <SearchBar> component. To manage the react side of things, I utili ...

An error of type `TypeError`: attempting to call `[0,1]` as a function arises while using an IIFE

Check out the following code: var numberArray = [0, 1] (function() { numberArray.push(2) function nestedFunction() { numberArray.push(3) function anotherNestedFunction() { numberArray.push(4) } console.log(num ...

Tips for retrieving the ajax results for multiple deferred calls using jQuery

I am struggling to utilize the jQuery deferred function as illustrated in the following code snippet. <script type="text/javascript"> var appUrls = { GetDataUrl : '@Url.Action("GetData")' }; ...

Trigger a notification from one webpage to another (PHP, JavaScript, HTML)

I'm currently working on a website that consists of both a receptionist page and a user page with multiple logins. The receptionist page displays a table listing all logged-in users, including their status (either ready or busy). This table is refresh ...

Securing API data: Utilizing encryption techniques in express and nuxtjs to deter scraping efforts

I'm looking for a secure way to encrypt my API data in order to prevent users from viewing it in the network tab or as plain text within objects like window.__nuxt__. Currently, I am following these steps: Encrypting data on the back-end using a sec ...

Repetitive points in Three.js

I've been working on creating a line in my scene, and it displays perfectly. However, when I attempt to create a mesh using the same coordinates that formed the line, I encounter errors indicating duplicate points. It's quite puzzling because I ...

Tips for managing a JSON response

Currently, I am facing a dilemma while using Python websockets to handle JSON objects. I have a working example with JavaScript that utilizes parseJSON as shown below: socket = io.connect("__socket address__"); socket.on("connect", function() {socket.emit ...

A guide on crafting a precise description for the 'module.exports' feature

I have successfully exported a function in the following way: module.exports = function (options: any): RequestHandler { // Do something } Now, I am attempting to define the exported function properly. However, I am unsure if this is the correct appr ...

Turn off the debugger statement using your web browser

I have a piece of code with the debugger keyword and I want to style it. However, every time I refresh the page, the browser's debugging window (IE, FF, Opera) stops at the debugger line. Is there a way to toggle or disable the debugger keyword throu ...

When loading JSON data dynamically into a D3 network visualization, the links may not be immediately visible

In my possession is a json file containing nodes and links defined with source and target attributes. { "links":[ {"_id": "5a4b2866235fa755b6576903", "target": 6746, "source": 2169}, {"_id": "5a4b2866235fa755b65768e3", "target": 67 ...

Is it possible to modify the icon displayed in an AJax response?

I have a link with an icon inside that I need to change when it is clicked. To achieve this, I attempted to use Ajax in the following manner: HTML <a id="#pl-esong234" class="social-button-song" title="Add in playlist" onclick="addInPlaylistSongs(234, ...