Shift the item directly beneath the position of the mouse pointer

I'm currently working on positioning an object called 'tracer' under my mouse cursor. You can view my jsfiddle here.

While researching, I came across this question, but I had difficulty applying it to my project.

In my scene, I have a basic setup with just a cube and a light. My goal is to have a pointer move beneath the mouse whenever it moves.

I've managed to achieve this using raycasting and intersecting objects. However, I also want the tracer to always follow the mouse, even when not intersecting with any objects. Here's the code for the object I want to position under the mouse:

var geometry = new THREE.CylinderGeometry( 0, 20, 100, 3 );
    geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 50, 0 ) );
    geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2 ) );
var tracer = new THREE.Mesh( geometry, new THREE.MeshNormalMaterial() );
scene.add( tracer );

This is how I retrieve the mouse position and set the tracer's position:

function onMouseMove( event ) {

    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;

    vector.set(
      ( event.clientX / window.innerWidth ) * 2 - 1,
      - ( event.clientY / window.innerHeight ) * 2 + 1,
     .5 );

    var dir = vector.sub( camera.position ).normalize();

    var distance = - camera.position.z / dir.z;

    var pos = camera.position.clone().add( dir.multiplyScalar( distance ) );

    tracer.position.copy( pos );
}

Despite my efforts, the tracer doesn't perfectly align underneath the mouse, instead moving slightly. Any assistance would be greatly appreciated.

Answer №1

This code snippet provides a method for keeping an object under the mouse within the z = 0 plane without creating a new THREE.Vector3() instance every time:

var mouse = new THREE.Vector2();
var vector = new THREE.Vector3();

function onMouseMove(event) {

    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;

    mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;

    vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );

    vector.unproject( camera );

    var dir = vector.sub( camera.position ).normalize();

    var distance = - camera.position.z / dir.z;

    tracer.position.copy( camera.position ).add( dir.multiplyScalar( distance ) );

}

Check out the fiddle for a working example: http://jsfiddle.net/ybndL7ro/6/

This utilizes three.js version r.70.

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

iOS Safari does not support equivalent regex unsupported lookbehind assertion

Trying to break a string into sentences using regex can be tricky. Unfortunately, the regex used in this example: var text = "Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Tips for tailoring content based on screen size

I am looking for a way to display different content depending on whether the user is viewing my website on a large screen (PC/tablet) or a small screen (mobile). While my site is responsive and uses bootstrap, I have a lot of content that is only suitable ...

How can I use Moment.js to show a custom message based on the current day of the week?

Currently, I am utilizing Moment.js to dynamically showcase various messages based on the day of the week. For instance, if it's: If it's Monday, I want it to display "It's Monday!" If it's Tuesday, I'd like it to show "Happy Tu ...

A guide on extracting data from an HTML table containing various input fields

I have a webpage with this table generated by a PHP script. What I need to do is extract the values from each of the 4 input fields and save them in separate JavaScript variables. Each button already has an onclick="fetchGrades(); trigger added. How can ...

The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete. Are there any t ...

Tips for selecting array [0] and turning it into a clickable link with JavaScript

My challenge lies in redirecting to a different URL when the user clicks on <a href="javascript:void(0)">Hotel Selection</a>. Below is my current progress. Grateful for any assistance! <div id="menu"> <ul> <li class= ...

Can you guide me on setting a background image URL for rails using javascript?

Within my Rails application, I have a collection of content paired with image buttons (each piece of content has an associated image). When a user clicks on one of these buttons, my goal is to display the corresponding image. All of my images are stored u ...

Manipulating browser geolocation with JavaScript

I am currently working on automating tests for a web application using Selenium. The application relies on obtaining the user's current location information through the HTML5 Geolocation API. However, for testing purposes, I need to simulate a fake lo ...

Establishing the Backbone router configuration

Having trouble identifying the issue with my Backbone router. Is there an error within this code block? The index route is functioning correctly, but the classes route doesn't seem to be triggered (for example, when I try navigating to a URL like loca ...

Access the input field value with PHP and store it in a variable

I previously looked into this issue, but the solution provided in the accepted answer did not resolve it for me: How to get input field value using PHP Below is an excerpt from my result.php file: ... <th> <form name="form" action= ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Why aren't the JavaScript stars shining once I've selected one?

I recently set up a star rating feature on my website by following the tutorial "Creating an Ajaxified Star Rating System in Rails 3". Although I managed to get everything working on the index page, I noticed that the stars do not remain lit up after bein ...

Can you confirm if this is the most efficient method for loading google-analytics and jQuery?

It's not necessary for jQuery to be loaded immediately on page load: Here is what I currently have: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '...']); _gaq.pus ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Could someone please guide me on how to use JQuery to set a radio button as checked?

<input type="radio" name="sort" value="2" id="myradio"> Is there a way to set this as the selected option using JQUERY? ...

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

In JavaScript, numbers cannot begin with a zero

var number = 05000; var addNumber = 1; When I try to add number + addNumber, the result seems to be incorrect. var total = number + addNumber; // the result is 20481 Refer to the image below for the quick watch result: https://i.sstatic.net/Hwz84.png ...