Changing 2D mouse positions to XZ world coordinates using ThreeJS

How can I convert mouse screen coordinates to ThreeJS world coordinates on the XZ plane?

I came across a code snippet that successfully converts mouse position to XY world coordinates, but I'm not sure how to modify it for XZ coordinates:

var vector = new THREE.Vector3();
vector.set((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1, 0.5);
vector.unproject(camera);
var dir = vector.sub(camera.position).normalize();
var distance = - camera.position.z / dir.z;
var position = camera.position.clone().add(dir.multiplyScalar(distance));
console.log("x: " + position.x + " y: " + position.y);

Answer №1

Found a solution by tweaking code sourced from this page:

                var x, y;
            //
            if (event.offsetX !== undefined) {
                x = event.offsetX;
                y = event.offsetY;
            } else {
                x = event.layerX;
                y = event.layerY;
            }

            var pos = new THREE.Vector3(0, 0, 0);
            var pMouse = new THREE.Vector3(
                ( event.clientX / window.innerWidth ) * 2 - 1,
                - ( event.clientY / window.innerHeight ) * 2 + 1,
                1);
            //
            var projector = new THREE.Projector();
            projector.unprojectVector(pMouse, camera);

            var cam = camera.position;
            var m = pMouse.y / ( pMouse.y - cam.y );

            pos.x = pMouse.x + ( cam.x - pMouse.x ) * m;
            pos.z = pMouse.z + ( cam.z - pMouse.z ) * m;

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

The sticky position is malfunctioning even when there is no parent element with the overflow hidden property

// observer for feature section let featuresSection = document.querySelector('#featuresSection'); let callbackFeature = (items) => { items.forEach((item) => { if (item.isIntersecting) { item.target.classList.add("in ...

How can I ensure that my asynchronous code is consistently executed on the same thread within a native node module?

In the process of developing a native node module in C++, I am creating a binding for a C library. It is crucial to note that certain objects within this library should only be accessed by a single thread. However, using uv_queue_work presents a challenge ...

"Encountering an issue when trying to choose a value from a select list using jQuery and the

What am I missing here or what is the correct approach to solve this? Take a look at the following code snippet: code snippet $(document).ready(function() { $(".metric_div").hide(); $("#solid_radio").click(function() { $("#solid").show(); ...

session failed to register the third variable

I have successfully implemented a login system in codeigniter. However, I am facing an issue where the session is not storing the user_type variable when I log in. I have reviewed my code multiple times but cannot seem to figure out what is causing this pr ...

Selecting a chained dropdown option using jQuery in CodeIgniter

I'm struggling with jquery and ajax, particularly in implementing a select box functionality. I am using CI and below is my code. I want the data in another select box "category" to change dynamically based on the selection in the "brand" select box. ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Unable to bind jquery click event to bootstrap col-md div

I am facing an issue with a div element that is defined as follows: <div class="col-md-4 single-signup wow fadeIn animated" data-wow-offset="10" data-wow-duration="1.5s"> Within this div, there is some content, like the following: <p><a i ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

What is the recommended approach for conducting backend validation?

As I develop a CRUD application using express.js and node.js, here is the backend API code that I have written: app.post("/signup", (req, res) => { const { name, email, password } = req.body; if (!name) { res.status(401).json("Please provide a n ...

When I navigate using state.go in my controller, the Ionic slide menu fails to appear

Hello everyone, I am currently using Ionic to develop my application and have implemented a slide menu. However, I encountered an issue where the slide menu fails to work when changing views using "$state.go". How can I resolve this? The Router : "use st ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

Issues with AngularJS ng-bind-html failing to display list items

I am working with a basic HTML document that looks like this... <ol> <li><strong>Test 1</strong></li> <li><strong>Test 2</strong></li> </ol> ...and I am attempting to connect it to a div ...

Manipulating a JavaScript object array: Eliminating objects with identical properties. Similar circumstances result in varying outcomes

Attempting to remove an object from an array if the age property matches using the provided codes. var state= [ {name: "Nityanand", age:23}, {name: "Mohit", age:25}, {name: "Nityanand", age:25} ] let a= [ ...

"Maintaining the jQuery carousel slider above the lightbox image for a seamless user experience

Being a newcomer to jQuery, I am currently relying solely on plugins. I recently installed a carousel slider that allows manual sliding to view images accompanied by text information underneath. By clicking on "more" at the bottom of the image/text box, an ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Styling a specific <div> element that contains multiple nested <div> elements sharing

Having multiple divs with the same class poses a challenge. When a user taps on one div, a slidetoggle() function reveals two buttons - "accept" and "reject". The goal is to change the background color of that specific div to green or red based on the butt ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Transform every DIV element into a TABLE, replacing each DIV tag with a combination of TR and TD tags

I have a code that is currently structured using DIV elements. However, I've encountered alignment issues when rendering it in EMAIL clients. To address this problem, I am looking to convert the DIV structure to TABLE format. Below is the original co ...

The functionality to remove table rows when checkboxes are selected is not functioning as expected in an Angular 7 application

My table contains data generated from a loop. When I click the edit button, additional buttons and textboxes are enabled. If multiple checkboxes are checked, the add buttons become disabled. However, if all checkboxes except one are unchecked, the add bu ...