Unreliable Raycasting with Three.js

I am attempting to identify clicks on my Plane mesh. I have established a raycaster using provided examples as instructions.

Below is the code snippet: http://jsfiddle.net/BAR24/o24eexo4/2/

Clicks made below the marker line do not register, even if they are within the plane (the marker line does not affect it).

Additionally, try resizing the screen. In such cases, even clicks above the marker line might not have the desired outcome.

Could this issue be related to the use of an orthographic camera? Or maybe an update to a necessary matrix is missing?

function onMouseDown(event) {
  event.preventDefault();

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

  raycaster.setFromCamera(mouse, camera)

  var intersects = raycaster.intersectObjects(objects);

  if (intersects.length > 0) {
    console.log("touched:" + intersects[0]);
  } else {
    console.log("not touched");
  }
}

Answer №1

When working with raycasting calculations in CSS, it's important to consider the impact of your styles. One approach is to adjust the margin for the body element:

body {
    margin: 0px;
}

For more insights on this topic, refer to THREE.js Ray Intersect fails by adding div.

Properly handling window resizing is also crucial. Here is a common pattern for accomplishing this:

function onWindowResize() {

    var aspect = window.innerWidth / window.innerHeight;

    camera.left   = - frustumSize * aspect / 2;
    camera.right  =   frustumSize * aspect / 2;
    camera.top    =   frustumSize / 2;
    camera.bottom = - frustumSize / 2;

    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

Take the time to explore the examples provided in the three.js library. In particular, check out .

Additionally, review this answer for a detailed explanation on correctly setting up an orthographic camera.

Version: three.js r.80

Answer №2

Here is a versatile solution that will function seamlessly, even if you are working with margins and scrolling on your website.

function onMouseDown(event) {
      event.preventDefault();

      var position = $(WGL.ctx.domElement).offset(); // utilizing jQuery to retrieve position 
      var scrollUp = $(document).scrollTop();
      if (event.clientX != undefined) {
           mouse.x = ((event.clientX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.clientY - position.top + scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      } else {
           mouse.x = ((event.originalEvent.touches[0].pageX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.originalEvent.touches[0].pageY + position.top - scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      }

      raycaster.setFromCamera(mouse, camera)
      var intersects = raycaster.intersectObjects(objects);  
    }

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

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

Is it possible to rearrange the node_modules directory?

Within the node_modules directory, there exists a large and extensive collection of modules. These modules are often duplicated in various sub-folders throughout the directory, with some containing identical versions while others differ by minor versions. ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

Issue in Jasmine test: 'Spy should have been invoked'

I've encountered an issue while writing a Jasmine test case for the following Angular function. The test case failed with the message "Expected spy [object Object] to have been called". $scope.displayTagModelPopup = function() { var dial ...

Executing a JavaScript function when an element is clicked using inline

Is it possible to write the code below in a single line? <a href="#" onClick="function(){ //do something; return false;};return false;"></a> As an alternative to: <a href="#" onClick="doSomething(); return false;"></a> functio ...

Discover the procedure for extracting a dynamic value from JavaScript to PHP

Could the centerId value be utilized and transferred to a php variable? const data = { action: 'ft-add-member', maritalStatus: $('.ft-entry-relationship-info .ft-marital-status ul li.current a').data('dropdown' ...

Enhancing speed on an extensive list without a set height/eliminating the need for virtualization

My webapp includes a feature that showcases exhibitors at an expo. The user can click on "Exhibitors" in the navigation bar to access a page displaying all the exhibitors. Each exhibitor may have different details, some of which may or may not contain data ...

Having trouble fetching values in Node.js after a certain period of time has passed

Whenever the page loads, the sha1 function is supposed to run and it should run after 5 seconds. var crypto = require('crypto'); console.log(sha1()); setTimeout(sha1, 5000); console.log(sha1()); function sha1() { var dt = dateTime.create(); ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

Toggling event triggers with the second invocation

At this moment, there exists a specific module/view definition in the code: define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], function($, _, Backbone, productTemplate) { var ProductView = ...

Is there a way to incorporate cell highlighting on IE?

I've implemented a method to highlight selected cells based on the suggestion from jointjs. It surrounds the cell with a 2-pixel red border, which works well in Chrome. However, I need the outline to work in IE as well. Unfortunately, when I reviewed ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...