Raycasting displaces object intersections in three.js when the camera is pitched

My latest development involves a raycaster that enables me to select objects within the scene using my mouse. The process is initiated like this:

this.raycaster = new THREE.Raycaster()

// then in onMouseDown event
this.raycaster.setFromCamera(this.mouse, this.camera)
let intersects = this.raycaster.intersectObjects(this.scene.children)

Everything functions correctly when I move the camera horizontally and rotate it around its axis. However, issues arise when I tilt the camera vertically. In such cases, the raycaster seems to intersect the object at a location different from where it appears on the screen. When looking above the object, the intersection point is also higher than the rendered position, while looking below results in an intersection point lower than expected.

this.yaw = new THREE.Object3D()
this.pitch = new THREE.Object3D()
this.camera = new THREE.PerspectiveCamera(70, this.width / this.height, 0.01, 50)

this.yaw.add(this.pitch.add(this.camera))
this.scene = new THREE.Scene().add(this.yaw)

// then in onMouseMove event
if (this.state === this.STATE.PAN) {
    this.yaw.translateX(-this.mouseDelta.x)
    this.yaw.translateZ(-this.mouseDelta.y)
}
if (this.state === this.STATE.ROTATE) {
    this.yaw.rotation.y -= this.mouseDelta.x
    this.pitch.rotation.x -= this.mouseDelta.y
}

I attempted to eliminate all transformations except for the vertical pitch, but the issue persisted. My suspicion is that the problem lies within the behavior of the raycaster rather than with the objects themselves, as it would be illogical for objects to render one way yet intersect differently.

Where could I have gone wrong? Could it be that the raycaster fails to cast from the camera's original position post-rotation?

Answer №1

An interesting issue arose with the raycaster in my project. It seemed to detect intersections at unexpected locations when I clicked above an object while pointing the camera above it. After some investigation, I discovered that the problem was due to incorrectly normalized mouse coordinates.

// Incorrect
this.mouse.y = (e.clientY / window.innerHeight) * 2 - 1
// Correct
this.mouse.y = -(e.clientY / window.innerHeight) * 2 + 1

By omitting the negation in the calculation for the y-coordinate, I inadvertently caused my mouse position to be mirrored within the scene. This resulted in the raycaster detecting intersections at opposite points from where I intended. For example, clicking at the top of the scene would register as a collision at the bottom.

This discrepancy only became apparent when I introduced pitching to the camera. When working with a flat geometry like a box, mirroring did not affect intersection detection because of the symmetry. However, once the camera angle changed, the oversight in normalizing the mouse coordinates became evident.

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

I encountered a problem with a three.js video example not functioning properly on my iPhone 6s, displaying only a black screen

An instance of a three.js video example not functioning on an iPhone 6s, only displaying a black panel. Interestingly, this example works perfectly on a PC desktop browser, but fails to load in Safari and Chrome on the iPhone 6s. ...

Conceal the main div when the nested div does not contain any content

Is there a way to hide the parent div EventsRollup when the child div RelatedEventsList is empty? <div class="EventsRollup"> <span class="EventsRollupTitle">CPR &amp; Health Safety Classes</span><br /><br/> ...

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...

Improving the method of extracting an ID from a form submission in Javascript and Django

My current code is functional, but I can't shake the feeling that it's a bit rough around the edges. Here's a simplified version of what I have: JQuery ready: <script type="text/javascript"> $(document).ready(function() { ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

When working with AngularJS routing, utilize a function for the templateUrl to dynamically load the appropriate template

Can a function be used as the templateUrl in angularjs routing? The $routeProvider official documentation states: templateUrl – {string=|function()=} Check out the $routeProvider official documentation here In javascript, a function is typically def ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

Attention all controllers summoned from one AngularJS document

Having recently delved into the world of AngularJS and Ionic, I've exhaustively searched for solutions both on this forum and beyond. Despite my efforts, nothing seems to be working. My goal is to create an application with a homepage featuring a ser ...

Getting a unique identifier from localStorage for a delete button is essential for efficiently removing specific items

Struggling to retrieve an id from localStorage despite multiple attempts. My localStorage data within events looks like the sample below. [{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21"," ...

Seeking advice on extracting data using Angular and transferring it using Node.js?

I have decided to switch my node.js application from using the EJS template engine to Angular. After successfully installing and setting up Angular, I am now trying to retrieve data using the $http service: (function($) { app.controller('EventCtrl ...

Export web application content to PDF through rendering on the server side

Our interactive web application, which includes multiple d3 charts, is built with vue. Currently, I am able to export our webpage to a PDF file by utilizing canvg and html2canvas to convert the content into PNG format. The PNG file is then transmitted to t ...

Ensure that the folder name contains specific characters

When working with AngularJS, I am developing a feature to create folders. One requirement is that if a folder name contains special characters like /, :, ?, "<", or |, an error message should be displayed stating "A folder name cannot contain any of the ...

Navigating through states in Angular-ui-router seamlessly while performing asynchronous calls

Attempting to initiate an asynchronous API call through the onEnter function to a new .state. onEnter: function(StatFactory){ StatFactory.getStats(function(res){ console.log("callback"); }); } What I h ...

What is the best method for scrolling down a JavaScript table using Selenium in Python?

My dynamic table is created using JavaScript. When the page loads, only the first elements are visible in the source code. This means that when I try to scrape values from the table, only the initial parts are retrieved. Before scraping, I need to scroll ...

Creating a Phonegap hybrid application that uses JavaScript redirection can cause an absolute positioned element to intermittently blink, revealing the content that lies

Currently, I am developing a Cordova project for both iOS and Android platforms. Within my project, I have two main pages: index.html and home.html. Each page contains an absolute positioned div (with loading feature) that is visible by default. Here is t ...

How can I make a function visible in function expressions when it's currently not showing up?

Here's a function expression that I have: var inputChecker = function(field) { return function() { if(field === '' || field === 'undefined' || field === null) { return false; } return true; ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...