Unexpected behavior detected in three.js and raycaster where conditional else statements fail to execute

I immersed myself into the world of three.js with the help of YouTube tutorials designed for beginners. One particular tutorial caught my eye where they showcased three spheres floating in space, each clickable.

Inspired by that, I delved deeper into creating a three.js scene and ventured to fabricate six 3D objects shaped like cylinders instead. My goal was simple - whenever a user clicked on an object, the camera would smoothly shift its focus towards that specific object, presenting relevant information on screen. Once the interaction was complete, the camera would gracefully transition back to its original position upon another click on the object.

I attempted to implement a logic flow where if you clicked on object 1 and it hadn't been interacted with before, the camera would zoom in and orient itself towards the object. If object 1 had already been clicked, the camera would elegantly reverse its movement back to the center point. This process would repeat for all five objects within the scene. While following along with the tutorial, one key aspect involved toggling a boolean variable to track whether an object had been selected or not. Integrating this mechanism into my code proved to be challenging as the Javascript system didn't seem to retain this vital piece of information properly.

After structuring five separate 'If' statements, I managed to witness the desired effect of tweens moving towards the objects but struggled to establish the functionality of returning the camera to its original state once interactions were completed.

Displayed below is a snippet of my code focusing on one of the cylinder objects for reference...

//CODE SNIPPET REPRESENTING ONE OF THE OBJECTS
const minigeometry1 = new THREE.CylinderGeometry(5, 5, 0.5, 50);
const minimaterial1 = new THREE.MeshStandardMaterial({ color: 0xffff00 });
const minicylinder1 = new THREE.Mesh(minigeometry1, minimaterial1);
minicylinder1.name = 'minicylinder1';
minicylinder1.position.z = 7.5;
minicylinder1.position.x = -28
minicylinder1.rotation.z = Math.PI / 2;
scene.add(minicylinder1);

//CLICK EVENT ANIMATIONS
//CAMERA MOVEMENT TWEEN FUNCTION//
function tweenCamera(finalPosition, tweenSpeed) {
    let initialPosition = new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);
    new TWEEN.Tween(initialPosition)
        .to(finalPosition, tweenSpeed)
        .onUpdate(() => {
            camera.position.set(initialPosition.x, initialPosition.y, initialPosition.z);
        })
        .easing(TWEEN.Easing.Cubic.Out)
        .start();
}

//DEFINE CAMERA AND OBJECT TARGETS


//RAYCASTER SETUP AND CLICK EVENT FUNCTION

...

If anyone could provide some insights or guidance on how to enhance my code, I would greatly appreciate it! Thank you in advance!

P.S. I acknowledge that my coding approach may need refinement, especially with using 'switch' statements. However, being a novice in programming, this project serves as my learning ground without any prior comparison experience.

Answer №1

Memo to self: while troubleshooting the disruption in the processing/displaying flow, I resorted to outputting messages to the console to pinpoint the exact issue. This led me to realize that I needed to place the

let coin1Clicked = false; . . . let coin5Clicked = false;

code OUTSIDE of my onClick function. Even though I originally intended them to be local variables rather than global variables, for some reason it was causing a problem. Once I changed them to global variables, the if...else statements started functioning correctly! Time to tackle GSAP next!

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

Is it possible to automatically adjust the cursor position in a textarea when the language is switched?

I am working with a textarea that needs to support both English and Arabic languages. In English, text is typically left-aligned, so the cursor should start on the left-hand side. However, in Arabic, text is right-aligned, meaning the cursor should begin ...

Utilizing internal PDF links in a Microsoft UWP application

In the process of developing a UWP app using javascript, I have created a list of links that are connected to PDF files stored locally in the app. The ultimate goal is to offer a collection of hands-free documentation for the Hololens (Windows AR) device. ...

What is the process of changing the name of an object's key in JavaScript/Angular?

In my possession is an established entity, this.data = { "part": "aircraft", "subid": "wing", "information.data.keyword": "test", "fuel.keyword": "lt(6)" } My objective is to scrutinize each key and if the key includes .keyword, then eliminat ...

Determining the total number of documents through aggregation while implementing skip and limit functionality

Is there a way to retrieve the total count of documents when implementing aggregation along with limit and skip in a query similar to the one below? db.Vote.aggregate({ $match: { tid: "e6d38e1ecd", "comment.top ...

Issue with showing helper text in MUI date picker when utilizing react-hook-form library

I have been using the react-hook-form library in combination with material-ui. One issue I am encountering is displaying a mandatory field error message for the date picker using the helper text attribute of MUI. Despite getting error messages for the text ...

Is there a way to spin around the focal point of an item in three.js?

In my current project, I am dynamically adding various objects of different sizes into a scene, one per click. My goal is to scale and position these objects accurately. Now, I am facing the challenge of rotating the objects around the Y axis at their cent ...

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

It appears that the ngRepeatWatch feature is causing a slowdown in Batarang

After reviewing the Batarang analysis of my AngularJS app, I have discovered the following: ngRepeatWatch | 64.2% | 136.0ms Surprisingly, this instruction takes up 10 times more time than the next reported instructions. Could this indicate that I am pot ...

Showing commute time using Google Maps API v3

Is there a way to display the travel time immediately when opening Google Maps API v3? If you want to show the driving time as soon as the map is loaded, check out this example that demonstrates switching between travel modes. While it's easy to set ...

Choose a dynamically generated html element without having to click on it

I've been looking for a way to target a dynamically-generated element (specifically a div with the class "date") using jQuery. While I keep finding references to the .on('click') method, it appears that this only selects the div once the pag ...

AngularJS - Import and save CSV files

I have set up a nodeJS program as the server and an AngularJS web application as the client. For generating CSV files, I am utilizing the "express-csv" library (https://www.npmjs.com/package/express-csv) Below is the code for the server side: Definition ...

Tips for testing Sequelize with Jasmine

In my database/index.ts file, I set up a Sequelize database using the code below: import { Sequelize } from 'sequelize'; const { DATABASE_DIALECT, DATABASE_HOST, DATABASE_PORT, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_NAM ...

Is there a way I can implement lazy loading of results without having to overhaul my entire Laravel + jQuery application built in the Single Page Application style?

I recently created a web application using the Single Page Application concept, but without utilizing any modern technologies or frameworks. In this application, I have a jQuery page that makes dynamic requests to a localhost - a Laravel instance that comp ...

Problem encountered when attempting to utilize the spread operator within .vue files in an Elixir Phoenix 1.3 application

I'm facing an issue while building Vue.js components that involve using the spread operator to map states from Vuex within my Phoenix 1.3 application. The JavaScript compile errors I encountered are causing some roadblocks: 26 | }, 27 | compu ...

How can I create a form in Django where selecting a drop-down option triggers an automatic submission?

I'm attempting to create a form that can pre-fill fields based on user selection from a drop-down menu. To kick things off, I want the form to automatically submit when an option is chosen from the drop-down list. Here is the code snippet I have been ...

Using JavaScript to convert the text within a div into negative HTML code

I am working with this specific div: <div class="signs" id="signs" onclick="toggle()">&#43;</div> It currently displays the positive sign. I have set up a JavaScript function that is triggered when the div is ...

Error in zone: 140 - Property 'remove' is not readable

I'm brand new to kendo ui. I successfully set up a prototype in my fiddle with a working delete confirmation window. However, when I try to integrate it into my existing codebase, I encounter an error: Cannot read property 'remove' at the li ...

Altering the texture of a mesh in Three.js can completely transform the appearance

I'm facing an issue with my model that contains multiple meshes. I only want to apply a texture to one specific mesh, but when I do, the entire model ends up with the same texture. What could be the mistake I'm making? function load_models(callb ...

The selected value is visible on the component, but once it is passed to the server action, it disappears

I am utilizing Nextjs14 and Supabase for my project. Currently, I have a select element where users can make a selection. The selected value is then passed as part of the formValue, which is expected to be received in the server actions as part of the For ...

What is causing my div exchange using .class to fail?

Struggling to convert this code from working with IDs to Classes. The code reveals one Div while hiding another based on the onClick event. Originally, it was straightforward because the div location was absolute. In the classes version, I need to revea ...