Transforming mouse clicks into 3-dimensional space using an orthographic camera

Three.js : rev 73

My current method for detecting object intersections in the 3D world with mouse clicks (orthographic setup) is as follows:

function onDocumentMouseDown(event) {
  event.preventDefault();
  console.log("Click");

  var mouse = new THREE.Vector2();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  var raycaster = new THREE.Raycaster();
  // update the picking ray with the camera and mouse position
  raycaster.setFromCamera(mouse, camera);

  // calculate objects intersecting the picking ray
  var intersects = raycaster.intersectObjects(scene.children);

  console.log("intersects: " + intersects.length);

  for (var i = 0; i < intersects.length; i++) {
    console.log(intersects[i].point);
  }

}

Unfortunately, I have noticed that the intersection detection is not very accurate, as it only works when clicking near the top left of the object's box.

jsFiddle: I would appreciate any assistance in understanding why this behavior is occurring.

Additionally, I am looking to determine the relative position of the click in 3D space when no object is selected - whether it is to the left, right, or below the box. Is it possible to utilize the ray itself to calculate this information?

Answer №1

It's important to accurately determine the mouse position for ray-casting:

  The mouse coordinates can be calculated as follows:
   mouse.x = ( (event.clientX -renderer.domElement.offsetLeft) / renderer.domElement.width ) * 2 - 1;
   mouse.y = -( (event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height ) * 2 + 1;

Ensure to fire the event listener when the window is resized. I have updated the fiddle once again, please check it now. Add a new function for window resize, the code is self-explanatory. I hope you understand it.

View the updated fiddle now:

Updated fiddle:- http://jsfiddle.net/gc1v0rza/5/

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

Exploring layered data through specific properties

Imagine a scenario where I have an array filled with data. Each element in this array is an object that could contain: an id some additional data a property (let's name it sub) which may hold an array of objects with the same properties (including t ...

ReactPlayer allows for the simultaneous playback of two files

I am trying to simultaneously play two files in reactjs using ReactPlayer. The first file is a video music clip that includes human voice audio, while the second file is music only without the human voice. My issue is that when I run the code provided, ei ...

Jquery UI slider malfunctioning would require troubleshooting

I am currently working on implementing slider functionality with jQuery. The slider is visible and functioning properly in terms of taking in values, however, the values are not displayed on the screen as expected. I have used console.log to track the ui.v ...

How to trigger a function to run only once in React when the page is accessed or refreshed

I'm currently developing a search feature using Algolia search functionality. Users can input a search term from another site, be redirected to the search page, and have the search executed automatically. Once on the search page, users must utilize t ...

Changing Page Content with Ajax Post-Redirect Pattern

Just had a quick question. Can the redirected page be affected by ajax's success function? The code will provide a better explanation. $.ajax({ type: "POST", url: "/admin/done", data: { ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Having trouble with a beginner problem that's hindering the functionality of my code

I have been struggling with a particular piece of code and it is driving me crazy as I am unable to locate the source of my error: $.post($form.attr('action'), $form.serialize(), function (result) { console.log(result); if (result.succes ...

What causes the discrepancy in rendering of three.js pointcloud between Mac and Windows operating systems with Intel HD graphics 4000?

I have been working on a Large PointCloud Viewer utilizing Three.js with over 10 million points. However, I have encountered a peculiar issue - the rendering appears different between Mac and Windows platforms. The first image shows the rendering on Mac ( ...

Passing a custom Vue component as a property to a parent component

Struggling to find answers to my unique question, I'm attempting to create an interface where users can drag or input images using Vue. I've developed a component called Card, which combines Vue and Bulma to create card-like objects with props fo ...

"error: unable to retrieve message channel name, result is undefined

Hey there, I'm currently experiencing an issue while trying to retrieve the name of a channel that I created. Strangely enough, it's returning undefined, even though I am certain that the channel exists. Let me share with you the code snippet wh ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Discover the secret to applying a gradient shade to the "border" element when it reaches full capacity with Vue's innovative Custom CSS package

Utilizing the package https://www.npmjs.com/package/vue-css-donut-chart#usage-with-all-the-available-props to create a "border" effect around images based on progress has presented a challenge. Specifically, achieving a gradient color for the border when i ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

The functionality of Bootstrap's JavaScript is dependent on the presence of jQuery - Reactjs framework

When attempting to combine bootstrap with reactjs, I encountered an issue with importing Bootstrap.js It seems that Bootstrap's JavaScript requires jQuery Below are some of the import statements I have tried: import $ from 'jquery'; imp ...