Track the Mouse with Three.js - Dynamic Object Movement

I'm currently working on a Three.js project where I need to create a sphere that follows the mouse cursor, similar to the functionality demonstrated in this example. The code snippet responsible for handling the mouse movement is as follows:

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
    mouseMesh.position.set(event.clientX, event.clientY, 0);
};

I've included a link to a JSFiddle containing the complete code, but it seems that according to the DOM, the mouseMesh object is undefined. Can anyone help me identify what might be causing this issue?

Thank you in advance for any assistance provided!

Answer №1

To make a sphere track the mouse, it is necessary to convert screen coordinates to threejs world position. Check out this link for reference.

Here is the updated code snippet

var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
vector.unproject(camera);
var direction = vector.sub(camera.position).normalize();
var distance = -camera.position.z / dir.z;
var position = camera.position.clone().add(direction.multiplyScalar(distance));

Answer №2

To accomplish this task, it is recommended to utilize a THREE.Raycaster. By setting a list of intersectObjects, you can obtain an array of objects that have intersected with the ray. This enables you to retrieve the position of the 'clicked' object from the returned list.

Essentially, the process involves projecting from 3D world space to 2D screen space. Renderers utilize projectVector to translate 3D points to the 2D screen. On the other hand, unprojectVector performs the inverse operation by unprojecting 2D points into the 3D world. In both cases, you need to provide the camera through which you are viewing the scene. Therefore, in this code snippet, a normalized vector in 2D space is being created.

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

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Is there a way to change the visibility of a form element within a directive with the help of

Consider a scenario where you have a basic form as shown below: <form ng-submit="methods.submit(formData)" ng-controller="diamondController" name="diamond" novalidate> <help-block field="diamond.firstName"></help-block> <input ...

Create an assortment of objects and add some dynamic movement to enhance the scene

If all of my items are placed into an array cube.push(new THREE.Mesh( new THREE.CubeGeometry(20,20,20), new THREE.MeshBasicMaterial({color: 0x202020,wireframe: true}) )); How can I achieve the following? cube.rotation.y += 20; Update: I attempted scen ...

Saving the current state of a member variable within an Angular 2 class

export class RSDLeadsComponent implements OnInit{ templateModel:RSDLeads = { "excludedRealStateDomains": [{"domain":""}], "leadAllocationConfigNotEditables": [{"attributeName":""}] }; oldResponse:any; constructor(private la ...

Encase the entire section following cloning with JQuery

Make sure to check out the jsfiddle demo linked below before proceeding: JSFIDDLE I need to transform the original structure as shown below: <div class="out"> <a>im here</a> <a>to save</a> <a>our</a> ...

Utilizing the code data:post.url from a blogger to create a clickable link paired with an image button

My website is logjik.com. I have implemented two social buttons in my posts, which also appear on my main page. I chose this solution because even though I am on the home page, I wanted to be able to share the link to my post (similar to how 9gag functions ...

Troubleshooting: jqGrid is not displaying the requested JSON information

I am implementing jqGrid in an ASP.NET page. Here is the structure in the .aspx page: <div id="divMy" style="width: 100%; overflow: auto;"> <div id="divMyTable" style="width: 97%; display: none;"> <table id="MyTable"> ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Resolution for Vue3: Understanding why a component instance's template ref cannot locate a defined function

LoginInfo.vue <script setup lang="ts"> import { rules } from './config/AccountConfig' import { reactive } from 'vue' import { ref } from 'vue'; import { ElForm } from 'element-plus'; const info = reac ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Dynamic form validation using jQuery

I am facing a challenge with validating a dynamic form on the user side. My goal is to ensure that if a user fills out one column in a row, they are required to fill out the remaining columns as well. For example, filling out the CC # should prompt the use ...

ReactPlayer allows for the simultaneous playback of two files

I am trying to simultaneously play two files in reactjs using ReactPlayer. The first file is a video music clip that includes human voice audio, while the second file is music only without the human voice. My issue is that when I run the code provided, ei ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Is it possible to observe the website functionalities and execute them directly from the console?

Question about JavaScript: Is it safe for a script tag to be visible in the body of the developer console and for functions to be run directly on the website? It raises security concerns, and there should be measures in place to prevent this kind of displa ...

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

ExpressJS, defining routes, locating controllers, and documenting APIs

Utilizing expressJS 4.X and nodeJS 6.x In the past, I was defining my routes in this manner : /** * @api {get} /users/:userId Get a user * @apiName GetUser * @apiGroup User * * @apiParam {Integer} userId Users unique ID. * * @apiSuccess (Success 2 ...

toggle between utilizing the page object API and the primary Nightwatch API

Currently, I am incorporating the page object model alongside nightwatch for my testing procedures. Encountering challenges while trying to interact with an element led me to execute some jquery. However, the 'execute' command is not featured in ...

Create a layout using CSS that features two columns. The left column should be fluid, expanding to fill all remaining space, while the right column should be fixed

I need to ensure that the Online Users div always remains at a fixed size of 200px, while allowing the chat window next to it to resize dynamically based on available space. Essentially, I want the chat window to adjust its width as the window is resized, ...