Inaccurate ray tracing using an orthographic camera in three.js

Currently working on a 2D CAD drawing viewer using the three.js library. I need the ability to click on objects within the scene to perform operations.

However, when utilizing an orthographic camera, I've noticed that the precision of the three.js raycasting is not up to my expectations.

Check out the code and demo here: https://jsfiddle.net/toriphes/a0o7td1u/

var camera, scene, renderer, square, raycaster;
init();
animate();

function init() {

  output = document.getElementById('output');

  raycaster = new THREE.Raycaster();
  // Renderer.
  renderer = new THREE.WebGLRenderer();
  //renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Add renderer to page
  document.body.appendChild(renderer.domElement);

  // Create camera.
  var aspect = window.innerWidth / window.innerHeight;
  var d = 20;
  camera = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 1, 1000);
  camera.position.z = 10;
  camera.position.x = 25;
  camera.position.y = 25;
  camera.zoom = 10
  camera.updateProjectionMatrix()

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableRotate = false
  controls.target.x = camera.position.x;
  controls.target.y = camera.position.y;

  controls.update();


  // Create scene.
  scene = new THREE.Scene();

  var points = [
    new THREE.Vector2(10, 10),
    new THREE.Vector2(40, 10),
    new THREE.Vector2(40, 40),
    new THREE.Vector2(10, 40),
    new THREE.Vector2(10, 10)
  ]

  var shape = new THREE.Shape(points);

  var geometry = new THREE.Geometry().setFromPoints(points);

  var square = new THREE.Line(geometry, new THREE.LineBasicMaterial({
    color: 0xFF0000
  }));
  scene.add(square)

  document.addEventListener('mousemove', findIntersections, false);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function updateMousePosition(event) {
  return new THREE.Vector3(
    (event.clientX - renderer.domElement.offsetLeft) /
    renderer.domElement.clientWidth *
    2 -
    1,
    -(
      (event.clientY - renderer.domElement.offsetTop) /
      renderer.domElement.clientHeight
    ) *
    2 +
    1,
    0
  );
}

function findIntersections(e) {
  var mouseposition = updateMousePosition(e);
  raycaster.setFromCamera(mouseposition, camera);
  const intersects = raycaster.intersectObjects(scene.children);
  output.innerHTML = intersects.length > 0 ?
    'Intersect: TRUE' :
    'Intersect: FALSE';
}

If you move your mouse near the red square, you'll notice that the intersection triggers before actually hovering over the edge.

I'm trying to figure out what might be causing this issue. Any ideas or suggestions?

Answer №1

The ability to detect intersections between lines relies on the .linePrecision attribute within the Raycaster object.

For example:

raycaster.linePrecision = 0.1;
const detectedIntersections = raycaster.intersectObjects(scene.children);

The numerical value assigned should be adjusted according to the scale of the scene. The value of 0.1 is a tested parameter that typically yields positive results in most scenarios. Unfortunately, the documentation does not provide further insight on this matter (unless I missed it during my research).

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

Utilizing React JS to assign various state values from a dropdown menu selection

In my project, I have implemented a dropdown list populated from an array of values. This dropdown is linked to a handleSelect function. const handleSelect = (e) => { handleShow() setCommunityName(e) } <DropdownButton id="dropdown-basi ...

Using three.js, add some empty space around each face of the Icosahedron geometry to create a distinct separation between them

Looking for guidance on how to separate each face of an icosahedron, similar to the image above. Does anyone have examples or concepts on how to achieve this? Each face of my icosahedron has a unique image texture as a material, so Shadermaterial is not an ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

I'm having trouble getting my innerHTML command to update anything on the webpage, and the reason is eluding me

Below is the code snippet provided: <div id="js"><button onclick="document.getElementById('js').innerHTML=('<form> <input type=text name=tick1></input> <input type=text name=tick2></input> ...

Exporting Maya files to Three.js JSON format allows for seamless integration of

Having an issue when exporting my model from Maya to JSON for ThreeJS. Many vertices appear to be in incorrect positions: You can download the model obj here: You can download the model js here: When I export, the options are: uv face vertex norma ...

Utilizing Javascript for a Stopwatch/Countdown in the Format: 00:00:00

I am currently working with this block of code: function startStopwatch() { vm.lastTickTime = new Date(); $interval.cancel(vm.timerPromise); vm.timerPromise = $interval(function() { var tickTime = new Date(); ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...

Axios fails to input data into the table

Having trouble with my axios request to insert.php. The variable note_text is coming back as null. I suspect it's because I'm not properly specifying the 2nd argument. My assumption was that there would be a variable like $ _POST['note_text ...

Unable to refresh data dynamically in pagination using DataTables

Currently, I am implementing a Datatable plugin to enable pagination on my HTML table. Within the table, there is a checkbox for selecting rows and each row possesses a unique ID. However, I am facing an issue when attempting to update cells of a specific ...

Battle of Kingdoms API ajax

When attempting to access Clash of Clans API information in this script, the following error is encountered: Refused to execute script from 'https://api.clashofclans.com/v1/leagues?authorization=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6Ij ...

Scrolling text box utilizing Jquery

Currently, I am utilizing a scrolling box that functions well * view here * under normal circumstances. However, when there is an extensive amount of content below it, such as: <article class="content"> ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

Whenever the Redux Store is accessed outside of a React Component, it will consistently retrieve the initial

When working with a React Redux app that is built on top of the Keftaa/expo-redux-boilerplate boilerplate and utilizes redux-persist, how can we retrieve the persisted Redux store from a non-React component? Issue: I am uncertain about the method to acces ...

Is it achievable to animate the offset with React Native Animated?

I am attempting to develop a dynamic drag and drop functionality, inspired by this example: My goal is to modify it so that when the user initiates the touch, the object moves upwards to prevent it from being obscured by their finger. I envision this move ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

What is the best way to combine a new object with an existing array of objects in JavaScript?

https://i.sstatic.net/QIRzO.png Here is an array that I need to modify by adding the object {"temperature":{"work":30,"home":24}} to the beginning: 0 : {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"} The code I am using is ...

Automatically adjust text size within div based on width dimensions

Dealing with a specific issue here. I have a div that has a fixed width and height (227px x 27px). Inside this div, there is content such as First and Last name, which can vary in length. Sometimes the name is short, leaving empty space in the div, but som ...

Update the controller variable value when there is a change in the isolate scope directive

When using two-way binding, represented by =, in a directive, it allows passing a controller's value into the directive. But how can one pass a change made in the isolated directive back to the controller? For instance, let's say there is a form ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...