Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the object and misses hitting it altogether. Below is the snippet of my code:

import * as THREE from "three";

// Initialization
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();

// Creating a sphere
const geometry = new THREE.SphereGeometry();
const sphereMaterial = new THREE.MeshLambertMaterial({
  color: "0xFFFFFF",
});
const sphere = new THREE.Mesh(geometry, sphereMaterial);
scene.add(sphere);

// Light setup
const ambientLight = new THREE.AmbientLight();
scene.add(ambientLight);

// Raycasting implementation
const mousePosition = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
window.addEventListener("mousemove", (event) => {
  mousePosition.x = (event.clientX / window.innerWidth) * 2 - 1;
  mousePosition.y = (event.clientY / window.innerHeight) * 2 - 1;

  raycaster.setFromCamera(mousePosition, camera);
  const intersects = raycaster.intersectObjects(scene.children);
  console.log(intersects);

  for (let i = 0; i < intersects.length; i++) {
    if (intersects[i].object === sphere) {
      (intersects[i].object as any).material.color.set("red");
    }
  }
});

// Animation loop
let step = 0;

const animate = (time: number) => {
  step += 0.01;
  sphere.position.y = 4 * Math.abs(Math.sin(step + 1));

  renderer.render(scene, camera);
};

// Camera setup
const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.set(5, 5, 10);
camera.lookAt(new THREE.Vector3(0, 0, 0));

renderer.setAnimationLoop(animate);

I am unsure whether raycasting is suitable for detecting moving objects in this scenario. If not, what alternative method would be recommended?

Answer №1

To resolve your problem, you can calculate the mouse coordinates by following this code snippet:

const rect = renderer.domElement.getBoundingClientRect();
mousePosition.x = ( ( event.clientX - rect.left ) / ( rect.right - rect.left ) ) * 2 - 1;
mousePosition.y = - ( ( event.clientY - rect.top ) / ( rect.bottom - rect.top) ) * 2 + 1;

Check out a live demonstration here: https://jsfiddle.net/9nhftaud/1/

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

Remove Request (MongoDB, express, handlebars)

Struggling with implementing a delete request in my application. I have a database filled with reviews that I manipulate through my app. Currently, I'm attempting to create a function that will remove a document from the database and then redirect th ...

Troubleshooting image loading issues when updating the base URL in an Angular JS project

I am trying to update the base URL for my application. Currently, when I load the application, the URL shows up as http://localhost:4200/#/, but I want it to be http://localhost:4200/carrom/ instead. To accomplish this, I modified the base URL and now th ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

"Silent Passageway: Connecting Node JS to ASW RDS MySQL Through a Secret

I am currently collaborating on a project with a partner. The backbone of our project is node js, and we are using an AWS RDS MySQL DB for our database. Our main challenge lies in establishing effective communication with the DB through SSH within NodeJS. ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

Trouble arises in TypeScript when defining a class - SyntaxError crops up

When I try to declare a class, I encounter an error: // The code below is from my test1.ts file class WDesign { wModel: string; wQuer: string; } let logWDesign = (wd : WDesign) => { console.log(wd.wModel + " " + wd.wQuer); } let wd1 : WDe ...

Can a Dashcode Webkit Web app be transformed into traditional HTML and CSS?

I have developed a blog using Dashcode, incorporating HTML, CSS, and Javascript to pull data from an xml file. It's pretty simple... My perspective on this is: 1. JavaScript should be compatible with all browsers (with some variations). 2. I may need ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

PHP cannot be utilized within the script tag

I'm currently using JavaScript to display an error message If a user inputs incorrect information and I add the following code: <?php $_POST["usernamereg"] ?> = usernamereg; the alert function stops working. However, if I remove this code, t ...

The function getServerSideProps does not return any value

I'm a beginner with Next.js and I'm currently using getServerSideProps to retrieve an array of objects. This array is fetched from a backend API by utilizing the page parameters as explained in the dynamic routes documentation: https://nextjs.org ...

Tips for closing 2 models in a React application

Currently, I am working on a project using ReactJs. One of the functionalities I am implementing is generating a user's gallery when the user clicks on their avatar. To achieve this, I am utilizing the react-grid-gallery package along with semantic ui ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

Limitations of GitHub's rate limiting are causing a delay in retrieving user commit history

I have developed a code snippet to retrieve the user's GitHub "streak" data, indicating how many consecutive days they have made commits. However, the current implementation uses recursion to send multiple requests to the GitHub API, causing rate-limi ...