Exploring Engaging Meshes with Three.js

As a newcomer to javascript and three.js, I have a question that may seem basic. Currently, I am exploring the example interactive/cubes/tween and attempting to modify it for a different purpose. Right now, when a MouseDown event occurs, the intersected geometry experiences a tween effect using the following function:

function onDocumentMouseDown( event ) {

                event.preventDefault();

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

                raycaster.setFromCamera( mouse, camera );

                var intersects = raycaster.intersectObjects( scene.children );

                if ( intersects.length > 0 ) {

                    new TWEEN.Tween( intersects[ 0 ].object.position ).to( {
                        x: Math.random() * 800 - 400,
                        y: Math.random() * 800 - 400,
                        z: Math.random() * 800 - 400 }, 2000 )
                    .easing( TWEEN.Easing.Elastic.Out).start();

                    new TWEEN.Tween( intersects[ 0 ].object.rotation ).to( {
                        x: Math.random() * 2 * Math.PI,
                        y: Math.random() * 2 * Math.PI,
                        z: Math.random() * 2 * Math.PI }, 2000 )
                    .easing( TWEEN.Easing.Elastic.Out).start();

                }

                /*
                // Parse all the faces
                for ( var i in intersects ) {

                    intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 );

                }
                */
            }

However, I'm interested in applying this effect only to the intersected geometry while giving a different effect to non-intersected ones. My attempt at achieving this is shown below:

function init() 
{

//JUST SOME CODE OF THE INIT()//
 //TRIANGLE//
        var triangle = new THREE.Mesh( new THREE.CircleGeometry( 50, 3, 0, Math.PI * 2 ), triangleMat );
        triangle.position.set( 70, 0, 0 );
        scene.add( triangle );
        sceneArr.push(circle);

        //SQUARE//
        var square = new THREE.Mesh( new THREE.CircleGeometry( 50, 4, 0, Math.PI * 2 ), squareMat );
        square.position.set( -35, 60.6218, 0 );
        scene.add( square );
        sceneArr.push( square );

        //CIRCLE//
        circle = new THREE.Mesh( new THREE.CircleGeometry( 50, 27, 0, Math.PI * 2 ), circleMat );
        circle.position.set( -35, -60.6218, 0 );
        scene.add( circle );
        sceneArr.push( circle );
}

Here's what my MouseDown function looks like:

function onDocumentMouseDown( event ) {

    event.preventDefault();

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

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children );


    if ( intersects.length > 0 ) {

        console.log( intersects[0] );

        new TWEEN.Tween( intersects[ 0 ].object.position ).to( {
            x: 0,
            y: 0,
            z: 0 }, 4000 )
        .easing( TWEEN.Easing.Elastic.Out).start();

        new TWEEN.Tween( intersects[ 0 ].object.rotation ).to( {
            x: 0,
            y: 0,
            z: Math.random() * 2 * Math.PI }, 2000 )
        .easing( TWEEN.Easing.Elastic.Out).start();

        for( var geo in sceneArr){

            if( geo != intersects[ 0 ]){

                geo.position.set( 50, 50, 0);
            }
        }

    } 

}

Unfortunately, my approach failed to deliver the desired result. How can I adjust my logic to make it work?

Answer №1

Managed to figure it out! The issue was with looping through meshes in the scene. I discovered the scene.traverse() method and updated the code accordingly:

function onDocumentMouseDown( event ) {

    event.preventDefault();

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

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children );


    if ( intersects.length > 0 ) {

        new TWEEN.Tween( intersects[ 0 ].object.position ).to( {
            x: 0,
            y: 0,
            z: 0 }, 4000 )
        .easing( TWEEN.Easing.Elastic.Out).start();

        new TWEEN.Tween( intersects[ 0 ].object.rotation ).to( {
            x: 0,
            y: 0,
            z: Math.random() * 2 * Math.PI }, 2000 )
        .easing( TWEEN.Easing.Elastic.Out).start();

        scene.traverse( function( node ) {

            if ( node instanceof THREE.Mesh ) {

                if ( node != intersects[ 0 ].object){

                 new TWEEN.Tween( node.position ).to( {
                    x: 50,
                    y: 50,
                    z: 0 }, 4000 )
                 .easing( TWEEN.Easing.Elastic.Out).start();

                }
            }

        } );


    } 

}

Found the solution on this Stack Overflow thread.

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

What is the process for reversing styles on the second click?

This is the script I've written: function displayPanel(index, colorCode) { buttons.forEach(function(button){ button.style.borderBottom=""; }); tabButtons[index].style.borderBottom="none"; panels.forEach(function(panel){ ...

How can JavaScript be used to populate a textbox value from a URL parameter?

After a user submits the script below, I want to redirect them back to the same page and fill in the dropdown menu and input box with values from the URL parameters. However, the fields are not populating after the redirect. Additionally, I need to remove ...

What causes the movement of li elements when hovered over and moved away from?

While trying to highlight a specific list item (li) element on mouse hover and simultaneously hide others using a script, an issue arises. The highlighted element "something" changes its position during hover, causing it to move out of the mouse cursor&apo ...

The issue I am facing is that the Vuetify v-data-table is failing to display the data

I'm relatively new to working with javascript and vue/vuetify. Currently, I have a v-data-table that I can fill with static data. However, I'm looking to populate it upon clicking through a Flask API call. This is what I have so far: index.htm ...

Incorporate a .php webpage into a div using Ajax and Javascript

(I'm still learning the ropes here.) I've created a page where users can toggle between different sorting options for posts. Depending on their selection, the corresponding content should be displayed. function loadNewContent() { $.ajax({ ...

Utilizing React Render Props to Pass References Between Components

Is there a way to access a ref that is passed between two external components using render props? I am trying to achieve something similar to this example usage. function Component() { // how can I retrieve the `ref` here? return ( <A> ...

Could the bottom scrollbar be made stationary?

My website features a sizable table with a bottom scrollbar due to overflow, which is essential. However, as the number of rows increases, the height of the table becomes an issue, requiring users to constantly scroll down to reach the bottom. Is there a ...

"Triggering an event after selecting and opening a file with an input of type file

Check out this snippet of HTML code: <input type="file" id="mysignature_upload" onChange="readURL();"/> We also have some Javascript code: function readURL(){ alert("Hello"); } A potential issue with this code is that the function readURL is on ...

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

Is there a way to define unique formatters for various transports in Winstonjs?

In order to customize the formatting of console and file transport in Winston, I decided to colorize console logs myself using the chalk module. Below is the code snippet I used to create the logger: this.logger = createLogger({ levels: { fa ...

The database has unfortunately registered an incorrect value for the "date" input after it was saved

When I select a date from the datepicker input field, it is being incorrectly saved in the database. I am selecting the date using the datepicker and then using AngularJS to send it to Spring MVC AngularJS: $scope.updateProjectDetails = function(detail) ...

Is there a way to verify if I am using yarn link properly?

Is there a way for me to determine if my locally linked package is being utilized instead of the remote version? Should it be visible on the development server of my local package? ...

Is there a way to remove createdAt and updatedAt from every query in Sequelize?

Currently, I am utilizing Node 14 and Sequelize to model an existing Postgres database. The tables that have already been created do not contain the createdAt or updatedAt columns, so my intention is to set up Sequelize in a way that it will never attempt ...

When the user clicks on an image, passing either the image name or image ID attribute

I need to send the image name to store.php whenever a user clicks on the image. Once I have the image name, I will query the database and display the corresponding result. However, I am unsure how to pass the image name when the user clicks on it. Can so ...

Issue with extraneous event being activated upon bootstrap collapse button usage

I have implemented a functionality using Bootstrap 5.2 where I have two buttons that can hide content by utilizing the Bootstrap collapse plugin. <div class="col-12 col-sm-auto"> <span class="pe-2"> ...

The post controller functions properly when an image file is present, but encounters issues when trying to create a

I'm struggling with my controller when trying to create a post. The issue seems to be related to the condition "if (req.file !== null)" which still executes even if no file is being uploaded (specifically in the picture field, as it should represent ...

Consistently shifting the Aframe camera towards the focal point

Is there a way to continuously adjust the view of my Aframe scene based on the current viewing direction? It seems like there are two key components needed for this: (1) obtaining the current viewing direction in the correct format, and (2) creating and u ...

What is the best way to divide a string based on multiple conditions in JavaScript?

Can someone help me retrieve a specific value? name // apple index // 1 LastName //Surname I am struggling with my current method due to a single condition '.' value = '#[pill(apple.1.Surname)]' const [var1, var2, var3] = value.split(& ...

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

selenium.common.exceptions.WebDriverException: Message: IndexError: array index out of bounds

I've been working on creating a web scraping tool that involves a Python script and a JavaScript code. The Python script is designed to call the JavaScript code, which then extracts relevant content from a web page and sends it back to the Python scri ...