To start, initialize a Raycaster:
const raycaster = new THREE.Raycaster()
Next, include this within your rendering function (the looped one):
raycaster.setFromCamera(mouse, camera)
If you're unfamiliar, camera
represents your camera and mouse
should resemble something like this:
const mouse = new THREE.Vector2()
window.addEventListener('mousemove', (event) => {
mouse.x = event.clientX / sizes.width * 2 - 1
mouse.y = - (event.clientY / sizes.height) * 2 + 1
})
For those who may not know; a Raycaster casts a ray and is utilized when determining intersecting objects. This allows for the implementation of desired mouse events on objects/meshes/geometries.
Don't overlook adding this line of code as well:
let currentIntersect = null
Subsequently, incorporate this into your rendering function (the looped one):
const modelsToTest = [model1, model2, model3, model4]
const intersects = raycaster.intersectObjects(modelsToTest)
if(intersects.length){
if(currentIntersect === null){
//perform actions
console.log('mouse enter event occurred!')
}
currentIntersect = intersects[0]
}
else{
if(currentIntersect){
//perform actions
console.log('mouse leave event occurred!')
}
currentIntersect = null
}
Congratulations, you've now simulated the mouseenter
and mouseleave
events!
The next goal is to implement the click
event. This can be easily achieved by inserting this code snippet somewhere in your script:
window.addEventListener('click', () => {
if(currentIntersect){
switch(currentIntersect.object)
{
case model1:
// execute actions for model 1 click!
break
case model2:
// execute actions for model 2 click!
break
case model3:
// execute actions for model 3 click!
break
case model4:
// execute actions for model 4 click!
break
}
}
})
Trust this information proves beneficial!