Guide to creating smooth mouse-tracking movements for an object on a flat surface in three.js

This code is currently functioning flawlessly:

const [value, update] = useReducer((x) => (x % 4) + 1, 20);
useFrame(({ controller }) => {
    if (element?.current) {
        controller?.ray?.at(value, element?.current?.position);
    }
});

Check out the live demo here: https://codesandbox.io/s/r3f-mouse-to-world-elh73?file=/src/index.js:311-315

Are you wondering how to incorporate a slight delay into the animation to prevent the object from instantly moving to the mouse position? Additionally, would you like to know how to introduce an offset so that the object is not directly at the center of the mouse pointer?

Answer №1

As always, the culprit was none other than me.

useFrame(({ raycaster }) => {
    const mouse = new Vector3(0, 0, 0);
    if (ref?.current) {
        //inject the raycast intersect point into mouse vec3
        raycaster?.ray?.at(dist, mouse);
        //get the object temp position
        const myPos = new Vector3(
            ref?.current?.position.x,
            ref?.current?.position.y,
            ref?.current?.position.z
        );
        //calculate the distance between mouse and object
        mouse.sub(myPos);
        //perform an ease operation here, adjust to increase ease effect
        mouse.divideScalar(10);
        //sum it up:
        myPos.add(mouse);
        ref?.current?.position.set(myPos.x, myPos.y, myPos.z);
    }
});

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

I encountered an issue where I was unable to execute an Ajax call on the Chrome browser while working with

My files are located in the C:/xampp/htdocs directory. I am trying to call: {"name":"john", "age":19.4} file from: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function ajax_json() { var hr = new XMLHttpRequ ...

JSX Script issue: the input prompt is missing

Greetings! I am currently working on a script to export JSON files from Adobe Illustrator. // Custom function for exporting prefixed objects function exportPrefixedObjects(doc) { // User input for prefixes and reference points var prefixInput = prompt( ...

Using Vue to bring in an npm module that does not have any exports

I'm facing a challenge when trying to bring in an npm package into a Vue component. This package (JSPrintManager - here) consists of a JavaScript file with no exports. Therefore, I'm unable to utilize the following import statements: import { J ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...

Is there a way to stop the YAML parser from including question marks in its output?

Looking to create a basic docker compose setup and integrate it into an existing file. The yaml parser found here seems promising, but I'm struggling with the question mark that appears in its output. This is the content of my current docker compose ...

Navigating through the properties of a JSON object and traversing the React state leads to encountering the error message 'state undefined'

Apologies if I seem a bit lost, but I'm attempting to assign a JSON object to a component's state for rendering purposes. This is the current setup within my component: render: function() { this.serverRequest = $.get(this.props.source, func ...

Iterate through a collection of objects, check their unique identifiers, and combine the objects together based on their

I am currently iterating through an array of objects in an attempt to extract the id and carId values from them. My code snippet looks like this: getIds(array) { for (var index in array) { var combinedIds = array[index]; if ...

What is the best way to utilize jQuery.post in order to push JSON data to a php script?

I have a JSON object in my JavaScript code stored in the variable dataStore. I've confirmed that JSON.stringify is working correctly by testing it with console.log(). However, as someone new to jQuery and CGI applications, I may be missing something. ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

Can one iterate over a JavaScript object using forEach() even if the keys are undefined?

During a code review, I came across the following code: var a = { ... }; // an object filled with key-value pairs for (var key in a) { if (!angular.isUndefined(key)) { do.stuff(); } } I am questioning whether key can ever be undefined or ...

Using Angular template reference variables for inputs to bind specific buttons with the same structure

Currently, I am exploring how to connect an input with a button in a row of buttons for opening images, inspired by an example shared by Mr. ruth. The layout of buttons in my web application resembles the following structure: topnav.component.html: <but ...

Manipulating Vue.js data within HREF attributes using PHP

Does anyone know how to successfully pass the data from Vue into PHP? I've attempted a few methods, but when I try to use the resulting link in the href attribute (href = $ where $ name), it shows a strange string instead of the expected URL from the ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

Tips for exporting an image from a threeJS scene

I am looking to export a 2D image of my scene by simply clicking a button on my HTML page. I have tried adding some code to my function, but unfortunately, it doesn't seem to work and the image is not downloading. (I am using Chrome as my browser) con ...

Inquiring about JavaScript's substring method in String.prototype

let vowels = "AEIOU"; let result = vowels.substring(0, 3); document.write(result); I'm puzzled as to why the output is AEI instead of AEIO. Is this due to the indexing starting from zero in programming languages? ...

Converting a Firestore collection into an array of objects using Firebase version 9

Currently, I am in the process of developing a React Web Application. My goal is to convert a firebase collection, which contains multiple documents, into an array of objects. Each object within the array should represent a specific document in the colle ...

Switch Bootstrap Tab

I have successfully implemented a bootstrap tab on my webpage and it is functioning as intended. Now, I am interested in adding an additional feature to the tabs. My question is, is it possible to toggle the content area if the same tab is clicked again? ...

Vue.js provides an interesting object that contains observed data

My axios request looks like this: retrieveData() { Axios.get( '/vue/get-data/', { ...