Manipulate the position of elements with Three.js as you move the mouse, pushing them away and then restoring their original position

https://i.sstatic.net/iQK6O.jpg

Hey there, currently I'm in the process of developing a project utilizing Three.js. The main concept involves allowing the user to interact with tessellated faces by hovering over them. Each mesh should be pushed away upon intersection with an invisible sphere and return to its original position when outside of that area. My inspiration comes from referencing this and this example, but I've hit a roadblock as I struggle to implement this functionality within Three.js.

Currently, my code allows for hovering over each face of a mesh, turning it red temporarily and reverting back to its original color once the mouse is no longer hovering. However, I am unable to replicate this behavior with regards to positioning. Here's where I suspect the issue lies:

if (intersects.length > 0) {

    // if the closest object intersected is not the currently stored intersection object
    if (intersects[0].object != INTERSECTED) {

        // Restore previous intersection objects (if they exist) to their original color
        if (INTERSECTED) {
            INTERSECTED.face.color.setHex(INTERSECTED.currentHex);
        }

        // Intersected elements
        INTERSECTED = intersects[0];
        var intGeometry = INTERSECTED.object.geometry;
        var intFace     = INTERSECTED.face;

        // Difference between intersected faces and geometry
        INTERSECTED.currentHex = intFace.color.getHex();
        intFace.color.setHex(0xc0392b);
        intGeometry.colorsNeedUpdate = true;

        // Identify the vertices of each face
        var intVertices = intGeometry.vertices;
        var v1 = intVertices[intFace.a],
            v2 = intVertices[intFace.a],
            v3 = intVertices[intFace.a];

        // Calculate the centroid of the selected face
        var intPosition = new THREE.Vector3();
        intPosition.x = (v1.x + v2.x + v3.x) / 3;
        intPosition.y = (v1.y + v2.y + v3.y) / 3;
        intPosition.z = (v1.z + v2.z + v3.z) / 3;
        console.log(intPosition);
    }

}

Through the use of console.log(), I can observe that the faces are being correctly identified along with their positions. But unfortunately, the sphere does not track the mouse accurately, and I require assistance with positioning. Below you'll find a link to a JSFiddle containing the complete code snippet.

Answer №1

Looking for a challenge? Check out this test related to the topic: https://jsfiddle.net/77xvepp7/

The functionality is not yet perfect; I've adjusted the camera for better visibility of the concept.

The core concept involves selecting a vertex on the surface as the "base point" and using it as a reference for moving other points within the triangle by the same distance. Failing to preserve the original values may result in incorrect triangle movements during subsequent rounds.

The approach includes calculating the mouse's distance from the "base point", iterating through all vertices, and adjusting their positions towards the base point. If the distance exceeds a defined threshold, revert the vertices to their original positions.

While exploring using a vertex shader for this task, a potential issue arises when each vertex moves in an opposite direction under the cursor, causing triangles to distort. Designating one point as the "base point" can address this concern.

  // Update geometry
  var geometry = backgroundMesh.geometry;
    for (var i = 0, il = geometry.faces.length; i < il; i ++) {

        var face = geometry.faces[i];

        if (face instanceof THREE.Face3) {

            var... (omitted for brevity)

       geometry.verticesNeedUpdate = true;
       geometry.normalsNeedUpdate = true;

    }
 }  

An existing challenge is accurately determining the mouse pointer's position in World Coordinates. Although resolving this issue currently eludes me, I decided to share this solution so you could build upon it further.

Answer №2

Ensure that you are updating your geometry properly by assigning values back to the vertices. Here is an example:

intVertices[intFace.a].update( intPosition );
intVertices[intFace.b].update( intPosition );
intVertices[intFace.c].update( intPosition );

intGeometry.verticesNeedUpdate = true;
intGeometry.normalsNeedUpdate = true;

Answer №3

You are experiencing an issue because the targetList you are attempting to use with ray.intersectObjects is not a type of THREE.Mesh. This is why you encounter an error when trying to access intersectedFace.acc.

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

There appears to be an issue with reading the property 'toLowerCase' of an undefined element, and I'm having trouble identifying the error

The variables I have initialized (globally): var audio; var LANGUAGE; var audioArray; var MEDIAARRAY; var WORDS; var SOUNDARRAY; This specific line is causing the error: var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInpu ...

What is the step-by-step process to upload a file along with JSON data using fetch and multer

My task involves uploading a file along with some metadata on a JSON object using the "fetch" JavaScript native function on the client side and Express with the multer middleware on the server side. Client Side: const formData = new FormData() formData.a ...

Use Sequelize to query a Many-to-Many relationship with conditions and a limit applied

I am currently working with the following relationship: Clients -> ProgramsClients <- Programs My goal is to execute the SQL query: SELECT * FROM Programs p JOIN ProgramsClients pc on p.id = pc.programId WHERE pc.clientId = 1 LIMIT 0, 100; I have ...

What is the best method for transferring images to a node.js server using Axios?

Is there a method to utilize axios for sending an array of images or a single image to node? My current axios code (implemented in react js on the frontend): onFormSubmit(event){ event.preventDefault(); let payload = this.state; console.log(" ...

What is the best way to utilize an AngularJS directive to send a POST request with all parameters from a form?

I have created a custom AngularJS form with Stripe integration using a directive. You can view the Fiddle for this project here: https://jsfiddle.net/u5h1uece/. HTML: <body ng-app="angularjs-starter"> <script src="https://js.stripe.com/v3/"> ...

Triggering a React hook again after a function has been called

As a newcomer to React hooks, I am working on a hook function that retrieves data from an API and displays it in a list: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [dep ...

Trouble with Angular 1.6 ng-repeat not showing search results

I can't seem to figure out why ng-repeat is not showing the search results. Here's what works: Using an HTTP GET request to retrieve all data from the database, and seeing the results displayed by ng-repeat. Sending an HTTP GET request with ...

An in-depth guide on incorporating an Editor into a Reactjs project

Currently, I am working with Reactjs and using the Nextjs framework. My goal is to integrate the "Tinymce" editor into my project and retrieve the editor value inside a formsubmit function. How can I achieve this? Below is my current code: const editor = ...

Why are Three.js ply files lacking in color?

I have been experimenting with the Three.js example located in the directory: three.js/examples/webgl_loader_ply.html By replacing their .ply file with my own (created in Blender). In Blender, I used Vertex Paint to paint vertices. Before exporting to . ...

Error message encountered: Module not found. It may not have been loaded yet

I am encountering an issue while attempting to utilize an npm module in my VUE component. I have imported the module and defined the necessary methods, but I am receiving the following error: Uncaught Error: No such module. (Possibly not yet loaded) De ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

Using services in Angular 6 CLI with dynamically added components

One of my recent projects involved creating a directive in Angular 6 called 'DeleteDirective' and integrating it with a service called 'DeleteService' to enable the deletion of items from the application. Once an item is deleted (handle ...

Amazon Lex: Transforming Speech to Text with Audio Technology

Is there a JavaScript SDK provided by Amazon for converting audio files to text using Amazon Lex? I am currently working on a Node.js application and would like to achieve this functionality. ...

Alter the color of the text within the `<li>` element when it is clicked on

Here is a list of variables and functions: <ul id="list"> <li id="g_commondata" value="g_commondata.html"> <a onclick="setPictureFileName(document.getElementById('g_commondata').getAttribute('value'))">Variable : ...

What is the best way to efficiently set up a scrolling text ticker for repeated use?

I am currently utilizing GreenSock/TweenMax for the creation of scrolling text, inspired by the design seen on this webpage: If you're interested in learning more about Greensock and its capabilities, take a look at their documentation here: While I ...

Utilizing a Promise in NodeJS and Express to effectively capture the writing functionality of the HTTP module

Currently, I am in the process of developing an Express application with the following components: NodeJS v8 express (latest version) As I delved into the workings of the onHeaders module and observed how it alters the HTTP headers, I became keen on lev ...

Ways to make normal material fade in THREE.JS

Recently, I have been exploring ways to create a smooth transition between different areas in THREE.JS. After some experimentation, I have come up with a method that I find quite effective. It involves manipulating the scene's fog by increasing its d ...

Else token error caught off guard

I am currently learning about if/else statements on Codecademy and keep encountering an error that says, "SyntaxError: Unexpected token else". Can someone please assist me? Below is the code I am working on: // Confirm if the user is ready to play conf ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

fetch promise not fulfilling as expected

There's a method I'm using to call an all-purpose fetch method defined in a separate JS file: export function detailedView(request,token) { let endpoint = 'api/v1/cbn/inventory/GetDetailRequest?RequestNo='+request['RequestNo&a ...