Interacting with a 3D model using the mouse cursor in a three

After stumbling upon the three.js library recently, I've been spending several days experimenting with it. I am eager to incorporate a mouse event into my project similar to this example where the head of the skull follows the cursor. However, I want to achieve this effect using only my JSON 3D model (unlike the example which includes the model's eyes and jaw animation for simulating a bite).

Here is the link to the example: https://codepen.io/interaktiv-ca/pen/XayZPx

Despite numerous attempts with this example, I have not been successful in integrating it into my project.

My basic setup looks like this:

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera ( 50, window.innerWidth / window.innerHeight, 1, 1000 );

camera.position.z = 15;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight);

document.body.appendChild ( renderer.domElement );

controls = new THREE.OrbitControls ( camera, renderer.domElement );

var loader = new THREE.ObjectLoader();
loader.load("/model/skull.json",function ( obj ) {
    var box = new THREE.Box3().setFromObject ( obj );
    var center = new THREE.Vector3();
    box.getCenter( center );
    obj.position.sub ( center );
    obj.rotation.y = Math.PI;
    scene.add ( obj );
});

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

animate();

Answer №1

To accurately determine the new position of your object, you need to set up a raycaster. Below is a sample code snippet that demonstrates how to achieve this:

onMouseMove(event) {
    const customVar = this;
    const mouseCoords = this.mouseCoordinates;
    mouseCoords.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouseCoords.y = -(event.clientY / window.innerHeight) * 2 + 1;
    raycaster.setFromCamera(mouseCoords, this.camera);
    const selectedObjects = [];
    selectedObjects.push(this.floorPlane); // Your object will move around this defined plane
    const intersections = raycaster.intersectObjects(selectedObjects);
    const intersectionItem = intersections[i];
    yourObject.position.copy(intersectionItem.point);

}

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 on retrieving specific information from PHP through jQuery AJAX

I have encountered an issue with my JavaScript file where I am sending an array of data to my PHP file. The problem is, when trying to print the name in #NAME and password in #PASSWORD, both values end up in both fields. You can see how it currently displa ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Create HTML elements based on the information in a JSON object

My goal is to create span elements for each word in my subtitle text, which is stored in a JSON object. Here is the JSON data I am working with: var sub_info = [ {'start': 3.92, 'end': 6.84, 'words ...

Strategies for efficiently updating specific objects within a state array by utilizing keys retrieved from the DOM

I am trying to figure out how to use the spread operator to update state arrays with objects that have specific ids. Currently, I have an array called "todos" containing objects like this: todos: [ { id: "1", description: "Run", co ...

Endless repetition occurs when invoking a function within a v-for loop

I've encountered an issue while trying to populate an array using a method, leading to redundant data and the following warning message: You may have an infinite update loop in a component render function. Below is the code snippet in question: ...

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

Invoke a function from a popup window, then proceed to close the popup window and refresh the parent page

When a link in the parent window is clicked, it opens a child window. Now, when the save button is clicked in the child window, I need to trigger a Struts action, close the child window, and reload the parent window. function closeChildWindow(){ document. ...

The infinite loop issue arises when the useEffect is utilizing the useNavigate hook

As I integrate the useNavigate hook within React to guide users to a specific page post-login, an unexpected infinite loop arises. Most sources online recommend utilizing the useNavigate hook inside a useEffect block; however, this method triggers a Warnin ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

What could be causing my Discord bot to remain offline even when I run the command node main.js?

After successfully installing node.js, I proceeded to type the command 'npm init' in the command prompt and then installed discord.js. However, upon installation of discord.js, a 'node_modules' folder was not added inside the project, w ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

Learn how to implement a split background effect by simply clicking the SPLIT button

let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.width = window_width; canvas.height = window_height; let hit_counter = 0; // object is created using class clas ...

Leveraging jQuery to interact with MySQL database in PHP Laravel framework

I seem to have hit a roadblock with my database, which is quite intricate. Here's the breakdown of the tables used for the questions: product - contains product details such as shoes productattribute - houses different variations of products like bl ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

Emphasize a passage by clicking on a different section of text

Seeking Assistance I am currently customizing this template which incorporates the MixItUp plugin. My query pertains to highlighting the "filter tab" upon clicking on the corresponding text when hovering over each image, a task I find challenging as a new ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...