I would like to understand the concept behind the direction parameter in three.js Ray

I am currently working on implementing collision detection for the meshes in my Three.js scene. I find myself confused about the functionality of the Raycaster and if I am using it correctly.

Below is a fiddle that illustrates the issue I am facing:

// Adding a cube at 40/40
geometry = new THREE.CubeGeometry(20, 20, 20);
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh(geometry, material);
mesh.position.setY(40)
scene.add(mesh);


// Adding Ray    
var origin = new THREE.Vector3(50, 0, 0),
    direction = new THREE.Vector3(-1,0,0),
    ray = new THREE.Raycaster(origin, direction),
    collisionResults = ray.intersectObjects([mesh]);
if(collisionResults.length!==0){
   alert('Ray collides with mesh. Distance :' + collisionResults[0].distance)
}

// Adding Arrow to show ray
scene.add( new THREE.ArrowHelper(direction, origin, 50, 0x000000));

Not working: http://jsfiddle.net/FredricBerling/LwfPL/1/

Working: http://jsfiddle.net/FredricBerling/LwfPL/3/

The fiddle demonstrates creating a cube and shooting a ray from the point (50,0,0) in a specific direction. However, there seems to be an issue where the collision is detected even when it shouldn't be.

An Arrowhelper is added to visually represent the direction in which the Raycaster shoots its ray.

Upon further testing, it appears that the direction in the Raycaster differs from the one in the Arrowhelper. The Raycaster seems to shoot the ray towards the origin of the scene (0,0,0), causing confusion.

EDIT: Thanks to Rob's suggestion, I have realized the importance of rendering the meshes to ensure that world matrices are properly applied. The fiddle has been updated with the corrected code that now functions as expected for testing the Raycaster behavior.

Answer №1

The seeming error you are observing is a result of the box's position being set, but its world transformation matrix has not been updated yet. Typically, this update occurs just before the rendering process.

To avoid receiving an incorrect hit, it is recommended to shift the raycast test to occur after the initial rendering (or manually invoke updateWorld()).

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

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

Data from Firebase persists even after removal

Currently utilizing firebase for my project, where each user object includes their list of favorites. The structure is illustrated below: https://i.sstatic.net/vm6w8.png In the favorites object shown, there was initially two records, but one was manually ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...

Combining the power of AngularJS with the versatility of sails

A project I'm working on involves utilizing sails.js for back-end and AngularJS for front-end. My plan is to use the Yeoman-angular generator https://github.com/yeoman/generator-angular to create the Angular app first. Once the front-end development i ...

What causes the function to return null when using router.get('/:x',..), whereas router.get('/foo/:x',...) works perfectly fine?

After weeks of struggling to identify the root cause of my issue, I finally pinpointed it. Now, I'm curious to understand the reason behind this behavior. I constructed an api for my mongodb server following the techniques I learned in school, utiliz ...

Error encountered while trying to authenticate user through post request

I have written a post route request function below to handle user login. However, I keep encountering 401 unauthorized errors when making the request. Can anyone suggest any modifications or refactorings that could potentially fix this issue? Thank you i ...

AngularJs is currently utilizing a combination of three filters for filtering, but disappointingly only two out of

I am working on filtering book information from a json file on a web page using AngularJS. So far, I have filters set up for Author, Title, Year Read, and Booktype, which are all functioning correctly. However, the filter for rating is not working as expec ...

Using innerHTML to replaceAll also modifies characters within the tags

I created a custom function to emphasize specific strings within a text by surrounding them with span tags and updating the content using the innerHTML property of the targeted element. However, I encountered an issue while working with innerHTML instead ...

After a PHP script is executed, a Bootstrap modal will automatically appear on the same page

Seeking assistance with integrating a bootstrap modal into a contact form submission. Despite multiple attempts, I have been unsuccessful in achieving this integration and now find myself at an impasse. My objective is simple: Upon clicking the submit bu ...

Why does the arrow function get executed right away once it is wrapped?

Currently, I am working on developing an app using react native. The goal is to have the screen automatically advance to the next one if there is no touch response within 5 seconds. I have implemented a function where pressing a button or entering text wi ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

Encountering the error message "Attempting to open an unclosed connection" when invoking a function from a child process in Node.js

I keep encountering the issue of "Error: Trying to open unclosed connection," even though I don't think it's related to a database problem. This has me puzzled because most fixes for this error point towards database connection troubles. My obje ...

Can types be imported from a module declaration?

In a scenario where I define a module as follows: declare module 'redux-form' { declare type FormConfig = { form: string, validate?: Function }; } Is there a way to utilize this type in my coding? If not, what are the different met ...

Strategies for managing repeated executions of UseEffect caused by fetching data from Firestore database

edit: made significant changes to the content of this question I am currently in the process of developing a booking application. I have noticed a considerable amount of rerenders occurring and, following the advice of @jpmarks, I have been attempting to ...

I am currently facing an issue where the code provided in the Puppeteer documentation is not functioning correctly due to an Un

I followed the code example on the Puppeteer documentation website but unfortunately, it's not working for me. I have Puppeteer 3.0.0 installed via npm. const puppeteer = require('puppeteer'); (async () => { const browser = await pup ...

html2canvas failing to render correctly with certain data URIs

This is how my div looks like https://i.sstatic.net/p7lN5.png After the rendering, the output appears like this. https://i.sstatic.net/FQO35.jpg Here is the html2canvas code snippet: html2canvas(document.getElementById('widgetElemet'), { ...

Changing the size of various types of images

Is there a way in JavaScript to automatically resize and fill in a block with fixed width using different images with various dimensions? I came across something similar, but it was in AS2. I'm unsure if it can be translated to JavaScript. var _loc3 ...

Tips for triggering a JavaScript function within WordPress using an inline function call

While setting up my plugin in the WordPress admin area, I encountered an issue with a form that stores user information. In my file input type, there is a JavaScript function call to my custom JavaScript that I have linked. Here is the line of code causing ...

Pause page scrolling temporarily in JavaScript while allowing the scrollbar to continue scrolling until the pause is lifted

I'm currently working on achieving a similar effect to the one found on this website: . On that site, as you scroll down, the 'HELLO' text moves to the side. I've managed to do that part successfully, but I'm facing an obstacle reg ...