Mouse movement event does not correspond to identical coordinates

I'm working on a 3D animation and trying to detect collisions with the mouse. I've attempted to make a ball follow the mouse, but it's not aligning correctly.

Here's a working example in CodePen

This function is borrowed from another answer on Stack Overflow, but it's not functioning as expected for me.

// Follows the mouse event
function onMouseMove(event) {

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

    // Make the sphere follow the mouse
    var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
    vector.unproject(camera);
    var dir = vector.sub(camera.position).normalize();
    var distance = - camera.position.z / dir.z;
    var pos = camera.position.clone().add(dir.multiplyScalar(distance));
    sphereInter.position.copy(pos);

    // Make the sphere follow the mouse
    sphereInter.position.set(event.clientX, event.clientY, 0);
}

As you can see, the blue ball is not in the same place as the mouse. How can I correct this issue?

Answer №1

To optimize your code, I recommend attaching the mousemove event listener to the renderer.domElement instead of the document. You can then utilize this snippet for determining the variables of mouse:

const area = renderer.domElement.getBoundingClientRect();

mouse.x = ( ( event.clientX - area.left ) / area.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - area.top ) / area.height ) * 2 + 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

Tips for restricting function invocations in JavaScript?

I am seeking a function called limitCalls(fn, maxCalls) which accepts a function fn and creates a new function that can only be called the specified number of times in maxCalls. Here is a test example: it('limitCalls', () => { const makeIncre ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Having trouble getting the JSONP request to render properly, encountering persistent errors

Need assistance with JSONP Rendering to HTML. The request is present in the source code, but I keep encountering errors on the foreach line. Any help would be greatly appreciated. <meta name="viewport" content="width=device-width, initial-scale=1"&g ...

What could be causing Jest to prevent me from using the node testing environment, especially when they have made changes to it?

I am currently working on testing a React component within Next.js using Jest. Jest made an official announcement regarding the change of default test environment to Node: Due to this update, the default test environment has been switched from "jsd ...

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Decode a JSON string that has already been encoded

Currently, I am dealing with JSON strings in which the quotes are not properly escaped. The strings are structured like this: { "foo" : "hello my name is "michael"" } Is there a practical way in JS/PHP to escape the quotes within the value without manual ...

Working with time durations in JavaScript

Is there a way to calculate the duration between a start time and an end time including both hours and minutes? Currently, I have code that only provides me with the hours. Is there any modification I can make to include minutes as well? If so, what chan ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

Having trouble with your onclick event not firing? Utilize jQuery to troub

Struggling to convert a hover trigger to a click event, but for some reason, no click function seems to work? Here is the current code that functions on hover... Current Working Code for Hover... $showSidebar.hover(function() { $wrapper.stop ...

How can I extract information from an iCal file to display the upcoming event?

Is there a method to extract information from an iCalendar file and display the most recent event using JavaScript or node.js? Your assistance on this matter would be greatly valued. Many thanks ...

JavaScript animation text not activating

I am working on a Bootstrap 5 carousel that displays two lines of caption per slide. I want to create an animation where the old captions fade out and move away as the slide changes, and the new captions fade in and move into place on the next slide. Howev ...

Issue encountered when attempting to execute a JavaScript AppleScript from another JavaScript AppleScript due to permissions error

I am in the process of organizing my .applescript files by separating them into different ones for better organization. Within my JS AppleScript file named Test.applescript, I am attempting to execute another JS AppleScript file called Group Tracks Depend ...

The error message states, "undefined cannot be used as a function."

For testing purposes, I am running checks on my Service using httpBackend. Specifically, I am focusing on a simple get request that needs to be tested for the response code. However, despite my efforts, I keep encountering this error: TypeError: undefined ...

Issues encountered when rendering textures from a canvas in Three.js

I've been working on creating a texture from a canvas. I managed to successfully render a blank canvas, but encountered issues when trying to draw an image on the canvas and then render it. This is the code snippet I am currently using: var canva ...

Prevent the onClick function of the outer div from being triggered by clicking on the inner div

Similar Question: Stop parent container click event from firing when hyperlink clicked My issue is <div onClick="someJScode();"> ... <div></div> ... </div> I need to prevent someJScode() from executing when the inner di ...

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

The resizing issue persists with Angularjs charts

I have recently developed a small web application using AngularJS and I have implemented two charts from the AngularJS library - a bar chart and a pie chart. Although both charts are rendering correctly, they are not resizing properly as the display size c ...

What is the best way to create a persistent alert in BootstrapVue that can be dismissed permanently?

I want to create a dismissable alert using BootstrapVue, but the alerts I've made keep reappearing every time I refresh the page. I'm looking for a way to make the alert get dismissed permanently after the user acknowledges it so they don't ...

Guide on changing label background color in React

Would you be able to guide me on how to change the background color of the label in react? I am utilizing react + material ui from this source. You can find information on writing CSS in js at this page. Some plugins like jss-nested are available for this ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...