Switch up the location of an object in Three.js by clicking the mouse

I'm attempting to replicate the click effect found on this particular website (enter and scroll in to witness the magic). The concept involves clicking on a picture, causing it to move front and center in front of the camera. Clicking it again sends it back to its original position. However, I am facing challenges when trying to revert objects to their original positions as the coordinates get lost during movement.

I have made some progress by storing the Vector3 in a global array and recalling those positions. But my current setup breaks if the camera is moved unexpectedly (the camera tends to move on its own for some reason).

This is what I've attempted:

var coordArray = [new THREE.Vector3(0, 0, 0)];
var raycaster = new THREE.Raycaster();  
var mouse = new THREE.Vector2();  
function onMouseClick(event){
    event.preventDefault();

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children, true)
    for(var i=0; i<intersects.length; i++){ 
        this.tl = new TimelineMax();
        originalCoords = new THREE.Vector3(intersects[0].object.position.x, intersects[0].object.position.y, intersects[0].object.position.z);
        coordArray.push(originalCoords);

        if(intersects[0].object.position.z != camera.position.z - 5)
            this.tl.to(intersects[0].object.position, 1, {x: 0, y: 0, z: camera.position.z - 5, ease: Expo.easeOut});
        else
            this.tl.to(intersects[0].object.position, 1, {x: coordArray[coordArray.length-2].x, y: coordArray[coordArray.length-2].y, z: coordArray[coordArray.length-2].z, ease: Expo.easeOut});           
    }
}

Any assistance would be greatly appreciated. I am fully prepared to face criticism for my lack of knowledge along with other minor details. The solution outweighs any embarrassment :p

Answer №1

I achieved the desired effect by saving the original position of the cube using its name as a reference.

    cube.position.set(-10, 5, -10);
    cube.name = "-10 5 -10";

Subsequently, in my click event handler, I parsed the name by splitting it at spaces and utilized the resulting values as coordinates for manipulation.

var raycaster = new THREE.Raycaster();  // defining raycaster for mouse click events
var mouse = new THREE.Vector2();  // specifying mouse coordinates
function onMouseClick(event){
    event.preventDefault();

    // Calculating mouse position when clicked
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children, true) // generating an array based on objects intersected
    for(var i=0; i<intersects.length; i++){ 
        this.tl = new TimelineMax();

        var initialPosition = intersects[0].object.name.split(" ");

        if(intersects[0].object.position.z != camera.position.z - 5){
            this.tl.to(intersects[0].object.position, 1, {x: 0, y: 0, z: camera.position.z - 5, ease: Expo.easeOut});
        }
        else{
            this.tl.to(intersects[0].object.position, 2, {x: initialPosition[0], y: initialPosition[1], z: initialPosition[2], ease: Expo.easeOut});
        }
    }

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

How can animations be disabled in Angular/Javascript?

I have been assigned the task of developing an Angular component for my company's applications that will include a toggle to disable all animations within the app for accessibility purposes. It is important to note that I am unable to go into each in ...

Aggregating multiple parameters in a D3 Treemap visualization

I have come across an interesting challenge while working on a project involving a zoomable treemap. I am currently exploring how to pass and aggregate multiple parameters within the treemap, similar to what is typically done in a zoomable treemap visualiz ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

Problem: Implementing a horizontal scrolling feature using Skrollr

I'm interested in creating a horizontal animation controlled by skrollr. As I scroll down, I want the elements on my page to move from left to right within my container. When all elements have the same width, setting the scrolling data from 100% to 0 ...

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

Problems arise when attempting to load a JSON file using the d3 library installed through npm

I recently added d3 through npm. In my package.json file, the dependencies section shows "d3": "^4.11.0". I attempted to load a simple JSON file using the following code: const d3 = require('d3') d3.json('jsonfile.json', (err, data) ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Most efficient method for dynamically changing HTML content with JavaScript

Can anyone provide guidance on how to switch HTML content using JavaScript? For example: if($sid == 0) {insert one HTML code} else {insert another HTML code} Which method is preferable - LESS, jQuery, CSS3, etc? ...

Identifying sluggish hardware or unresponsive browsers using JavaScript

My site features numerous CSS animations and transitions that run very slowly on specific browsers and older hardware. I want to avoid user-agent sniffing; is there a way to identify browsers or hardware configurations using JavaScript or a JS library, and ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

The radio input is not being properly checked using ng-checked in Angular

The ng-checked attribute is causing issues in the application, specifically with radio buttons. It seems to be working fine for checkboxes but not for radio buttons. <input type="radio" class="radio" name="job_class_radio" ng-checked="key===jobClassDat ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Accessing a global variable in AngularJS while using ng-data-repeat functionality

Currently in my Angular project, I am displaying block information using the ng-data-repeat directive and accessing various values. Below is a snippet of a table utilizing this repeat feature: <tr class="fader" ng-repeat='b in blocks'> ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

expanding animation featured on Wikipedia

Have you ever noticed that when you visit a Wikipedia page on Chrome and use the ctrl+scrollup or ctrl+scrolldown command, the page resizes in a smooth animation? Do you wonder how this effect is achieved? (Interestingly, in Firefox, only the links in th ...

Learning to monitor for incoming messages in a Discord channel from the ground up

I am eager to understand how to detect new messages exclusively using requests made to the Discord API. While I have mastered loading messages by fetching , I am struggling to grasp how to listen for incoming messages. It appears that this feature is not ...

Tips for: Minus a CSS property from a JavaScript variable height?

Is there a way to deduct the navbar_height by 2rem in the code snippet below? navbar_height = document.querySelector(".navbar").offsetHeight; document.body.style.paddingTop = (navbar_height - 2 ) + "px"; Appreciate your help! ...

Issue with JQuery on("submit") event not triggered upon first click

I'm currently using JQuery to check the size of an input field after submitting a form: <!DOCTYPE html> <html lang="en> <head> <title>Page 1</title> <meta charset="utf-8"/> <script src="https://ajax.google ...