I’ve been trying to catch a click event on a specific mesh for a while now but I can’t seem to get it right for some reason. I have 3 meshes in my scene. Now when I click on the first one it works. But when I click on another one after that first click things start getting messy.
I want to set a click event on a specific mesh and when this event gets triggered, I want the other objects to stay exactly the way they are. The event callback should only change the mesh that triggered it.
Here’s my code example:
let geometry1 = new THREE.CylinderGeometry(0.02, 0.02, 0.06, 60),
geometry2 = new THREE.CylinderGeometry(0.02, 0.02, 0.06, 60),
geometry3 = new THREE.CylinderGeometry(0.02, 0.02, 0.06, 60),
material1 = new THREE.MeshBasicMaterial({ color: 'red' }),
material2 = new THREE.MeshBasicMaterial({ color: 'red' }),
material3 = new THREE.MeshBasicMaterial({ color: 'red' });
this.btn1 = new THREE.Mesh(geometry1, material1);
this.btn1.position.set(-0.5, -0.54, -2.51);
this.btn1.rotation.set(0, 1.4, 1.55);
this.sketch.scene.add(this.btn1);
this.btn2 = new THREE.Mesh(geometry2, material2);
this.btn2.position.set(-0.4, -0.54, -2.51);
this.btn2.rotation.set(0, 1.4, 1.55);
this.sketch.scene.add(this.btn2);
this.btn3 = new THREE.Mesh(geometry3, material3);
this.btn3.position.set(-0.3, -0.54, -2.51);
this.btn3.rotation.set(0, 1.4, 1.55);
this.sketch.scene.add(this.btn3);
this.buttons = [
this.btn1,
this.btn2,
this.btn3,
];
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(this.mouse, this.camera);
let intersects = raycaster.intersectObjects(this.buttons );
for (const intersect of intersects) {
if (intersect.object === this.tv.btn1) {
this.isClicked(() => { // tv button 1 clicked
let value = -2.51;
let color = "red";
if (intersect.object.position.z === -2.51) {
value = -2.52;
color = "green";
}
gsap.to(intersect.object.position, {
z: value,
});
intersect.object.material.color = new THREE.Color(color);
});
} else if (intersect.object === this.tv.btn2) {
this.isClicked(() => { // tv button 2 clicked
let value = -2.51;
let color = "red";
if (intersect.object.position.z === -2.51) {
value = -2.52;
color = "green";
}
gsap.to(intersect.object.position, {
z: value,
});
intersect.object.material.color = new THREE.Color(color);
});
} else if (intersect.object === this.tv.btn3) {
this.isClicked(() => { // tv button 3 clicked
let value = -2.51;
let color = "red";
if (intersect.object.position.z === -2.51) {
value = -2.52;
color = "green";
}
gsap.to(intersect.object.position, {
z: value,
});
intersect.object.material.color = new THREE.Color(color);
});
}
}
isClicked(callback) {
this.renderer.domElement.addEventListener('click', callback);
}