Using ThreeJS to project a mouse click onto the XZ plane

I am currently working on implementing offline routing in a 3D map within a ThreeJS scene. My goal is to allow the user to click on a point and have a cube navigate to that point. While the navigation functionality is working correctly, I am facing an issue where the clicked point is not accurate. The flat map I am using is a plane in XZ coordinates with the Y axis pointing up. Within the scene, I have Orbit Controls which modify the position argument of the camera when orbiting, leading to inaccurate raycasting with my current setup. I need to obtain the correct XZ coordinates regardless of the orbit state. While I have achieved accurate coordinates for traditional raycasting in 3D, this approach is not suitable for my needs. I have tried the basic method from the ThreeJS documentation for raycasting, followed the solution provided in this question, and attempted unprojecting the mouse click using Vector3.unproject() without any success.

You can view an illustration of my issue in this jsfiddle, which also includes some important explanatory comments.

Answer №1

There were some bugs in my initial code, but after reworking it and running some tests, I successfully managed to retrieve coordinates from the intersected plane. This was achieved by incorporating Orbit Controls into the solution. Here's a snippet of how my 'onMouseClick' function currently appears:

var mouse = new THREE.Vector2();
   var rect = scope.renderer.domElement.getBoundingClientRect();
    mouse.x = ( ( event.clientX - rect.left ) / rect.width ) * 2 - 1;
    mouse.y = - ( ( event.clientY - rect.top ) / rect.height ) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);
  var intersection = raycaster.intersectObject(plane);
  //example box for position visualisation
  box.position.copy(intersection[0].point);
  box.position.y = 0;

Utilizing Three.js version r.87

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

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

Activate a function when the VueJS countdown timer hits zero

I've successfully created a countdown timer in the template that decrements a number perfectly. Now, I'm facing the challenge of triggering a function declared within the methods section once the countdown reaches 0. Despite attempting to check i ...

Reading the final element in the series with an IF statement

Something strange is happening with my code. I have a variable called racks_value that gets updated based on calculations performed on the page. Despite manually setting racks_value to 2 and confirming it with a console log, after running a series of IF st ...

Having trouble loading Three.js in JavaScript file using npm install?

I am encountering a problem when trying to include Three.js in my JavaScript file without using the HTML script element. The error message I receive is "Uncaught SyntaxError: Cannot use import statement outside a module". Although my Three.js code runs suc ...

Troubleshooting script error: Dealing with Ineffective Redirects

I am currently using a JavaScript code that allows users to jump to a directory by typing its name. Here is how it functions: If the input field is left empty, the user will be directed to a page called "error.html" which displays the message "This field ...

What's the reason behind express-rate-limit not performing as anticipated?

There seems to be an issue with the enforcement of the rate limit I specify in my code. Instead of lasting for 35 minutes as intended, it only lasts for about 20 seconds. Additionally, continuously making requests seems to reset the time limit, which is un ...

Testing the revised react component through unit testing with jest and enzyme

I am currently working on writing the test file for this code snippet. Here is my approach: import React from 'react'; import renderer from 'react-test-renderer'; // import { mount } from 'enzyme'; import LazyToastMessage from ...

What steps can I take to stop Google Maps from resetting after a geocode search?

As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facin ...

Error code 403 has been reported by Stripe's payment_init.php as a forbidden request

Having some trouble incorporating a Stripe payment method into my web application. I've hit a roadblock: payment_init.php isn't loading when I'm redirected to the page. Instead, I'm greeted with a 403 Forbidden error code ("Forbidden. Y ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...

Troubleshooting a Node.js problem with variable scope

I'm working on a nodejs route that downloads a URL as an mp3 using npm-youtube-dl. I have a download directory being monitored with chokidar for new files, and once a file is added, I save the file link. After the download completes, a function is cal ...

Attempting to save data to an external JSON file by utilizing fs and express libraries

I've encountered a challenge while attempting to serialize an object into JSON. Despite my best efforts, I keep encountering an error that has proven to be quite stubborn... Below is the code snippet that's causing the issue: APP.post('/api ...

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

What is the correct way to securely send the username and password from a ReactJS frontend to the backend for authentication?

My React application includes an onChange function on a form that collects username and password. Upon submission, the username and password are sent to the server side using redux dispatch in Node.js. On the server side, I am authenticating the credentia ...

Information is cleared before it is transmitted

Let's begin with the following code: JavaScript: function keyPressed(e) // function for key press event { if (e.keyCode == 13) // 13 represents the enter key { $(this).val(""); } } $(document).ready(function () { $(' ...

Adjusting the X-Axis Labels on a Scatterplot using Chart.js 2

I'm working with Chart.js 2 to create a scatter plot using Epoch timestamps for the x coordinates and integers for the y coordinates. Is there a way to customize the x-axis labels on the graph to show dates in a more readable format? Update: I am cur ...