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.