Using THREE.js to create interactive clickable objects is a fun way to engage users. By clicking on a cube, you can trigger the appearance of a second cube,

I have a goal in mind. When the first box is clicked, I want a second box to appear. Then, when the second box is clicked, I want the color of the original cube to change. I've managed to achieve the first step, but I'm unsure how to implement the last step. Below is my code...

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link rel="stylesheet" href="css/main.css" />
      </head>
      <body>
        <script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
        <script>
          var camera, scene, renderer;
          var geometry, material, mesh;

          init();
          animate();

          function init() {
            // Code for initializing the scene and objects
          }

          // Hover effect on cubes
          var raycaster = new THREE.Raycaster();
          var mouse = new THREE.Vector2();
          function onMouseMove(event) {
            event.preventDefault();
            // Code for handling mouse movement and interaction with cubes
          }

          // Animation loop
          function animate() {
            requestAnimationFrame(animate);

            // Code for animating the scene and objects
          }

          window.addEventListener("click", onMouseMove);
        </script>
      </body>
    </html>

Answer №1

To start off, it's important to give your mesh a name.

For example, you could name it rotatingMesh and staticMesh. Assigning names helps keep track of which 3D object is being clicked on.

Now, if the second cube is clicked, it should turn yellow. To achieve this, you need to listen for clicks on the second object as well (as demonstrated below)

for (var i = 0; i < intersects.length; i++) {
    if(intersects[i].object.name === 'staticMesh') {
        // Change color of rotating mesh to yellow
        mesh.material.color = new THREE.Color(1,1,0)
    } else {
        var geometry1 = new THREE.BoxGeometry(0.5, 0.5, 0.5);
        var material1 = new THREE.MeshLambertMaterial({ color: 0xce2121 });
        var mesh1 = new THREE.Mesh(geometry1, material1);
        mesh1.name = 'staticMesh'
        mesh1.position.y = 1;
        scene.add(mesh1);
    }
}

The code snippet below shows an example of how this use case can be implemented. If you have any further questions, feel free to ask.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <script src="https://cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
    <script>
      // JavaScript code here
    </script>
  </body>
</html>

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

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

Preventing constant component rerendering in ReactJS when input text field changes

I am new to using reactJs and am currently working on implementing user Authentication functionality. I have divided my project into two components: the header component, which includes a navbar with react-router routers, and the login component, which con ...

Unable to load module.exports = require("three/examples/jsm/loaders/GLTFLoader") in Next.js due to an error

Currently, I'm utilizing react-three-fiber, three, and nextjs to showcase some birds as a typical example in the realm of threejs! Below is the index file from a nextjs application: import React, { useRef, useState, useEffect } from 'react' ...

How can I modify the text that appears when hovering over an element?

Can the displayed text be altered on mouse hover? For instance, can I change the text of a H1 tag when hovering over it using HTML, CSS, and JavaScript? ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Dealing with Three.JS, Amazon S3, and the challenges of access control origin errors in hosting JavaScript files

Overview In order to showcase models stored on Amazon S3, we rely on the use of the Three.JS Javascript library for visualization. For loading models, I exclusively utilize the JSONLoader due to its comprehensive toolchain support. Other formats such as ...

Creating a new row dynamically in reactable is a useful feature that can enhance the

My goal is to add a new row when clicking on an accordion, specifically while expanding using reactable. I have included the expected outcome below. I have displayed structured data in a table using Tr and Td from reactable, but I am uncertain how to add t ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

Unable to operate a playlist application

I am currently facing an issue while trying to run a small application using an HTML kit. The application consists of two forms - one for text input and the other for a button. The goal is to save the text entered in the text input form into a list when th ...

Adjust regex for image URLs in JavaScript to handle unique and special cases

Does anyone have experience with using image URL regular expressions to validate images in forms with the ng-pattern directive? I'm currently facing difficulties handling cases like https://google.com.png. Any assistance would be greatly appreciated. ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

Animating SVG elements with the rotation property in SVG.js

Currently, I am utilizing Javascript, Jquery, SVG, and SVG.js in my project. My goal is to rotate a circle around its origin while it's animating. The issue arises when the animation keeps restarting abruptly, causing a jittery motion. Here is the ini ...

Tips for concealing information that is scrolled beneath a translucent layer

In the scenario where you have two overlapping divs, with the top one being transparent, the goal is to have the bottom div hide as it goes under the top transparent div when scrolling. It's important that the bottom div's visibility is not compl ...

Adding data dynamically to XSLT through jQuery upon button click: A step-by-step guide

Can you provide guidance on how to dynamically append data in XSLT upon button click using jQuery? This is what I have tried so far: <button onclick='clickBtn()'>append</button> JavaScript function function clickBtn(){ cons ...

Is it no longer possible to use v-for to iterate over translations in Nuxt 3 and @nuxtjs/i18n?

Imagine having an Array stored in our translations file en.js section: { title: 'This value is a string and it works perfectly', highlighted: [ { title: 'Highlighted title 1', text: 'Highlighted text ...

What is the method for selecting the desired month on a primeng calendar with multiple selection enabled?

I am looking for a solution to make my inline primeNg Calendar display the month of a specific date in the model, and when I remove dates from the model, I want it to show the current month. I have tried using defaultDate={{value}} and minDate={{value}}, a ...

Incorporate a PHP variable into JavaScript

class Map { public $Id; public $longitudes; public $latitudes; public $lat_init; public $lng_init; public static function createMap($Id){ global $latitude, $longitude; $dbh = Database::connect(); $query = "SELECT * FROM `cartes` WHERE Id=? "; ...

Creating an HTML list based on the content of a textarea input

Looking for some guidance in creating a dynamic list using JavaScript. The goal is to have user input data into a textarea, and upon clicking the submit button, generate a list in HTML. HTML: <body> <div class="container"> <di ...

JavaScript post method is failing to work, while it successfully runs in POSTMAN

Attempting to send a message to Android devices through a POST request to Firebase Cloud Messaging. When using POSTMAN, the server responds with a success response 200. However, when attempting the same operation with JavaScript using an AJAX request, I r ...

Express is unable to fetch the /images resource

While utilizing Express, I have encountered an issue where JavaScript allows me to access images, but when trying to directly implement an image route in the src attribute like <img src="images/background.png"> The localhost indicates that it is u ...