Having just completed my first tutorial in threejs as a novice, I am now facing a challenge. I am trying to create a hover effect on a basic cube shape where it grows in size when the mouse pointer hovers over it and shrinks back to its original size when the pointer moves away. I believe using an If Statement would be the solution, but I am struggling to find documentation or examples on how to implement this in threejs. Below is the code I have so far:
// Scene and Camera settings
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
)
camera.position.z = 5;
// Renderer settings
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setClearColor("#e5e5e5");
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//Prevent malforming of renderer when resizing browser
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
//Raycaster and mouse to detect intersections
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
//Cube settings
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshLambertMaterial({
color: 0xFFCC00
});
var mesh = new THREE.Mesh(geometry, material);
mesh.rotation.set(0, 1.75, 0);
scene.add(mesh);
//Light settings
var light = new THREE.PointLight(0xFFFFFF, 1, 500);
light.position.set(10, 0, 25);
scene.add(light);
//Render
var render = function() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
//onMouseOver event
function onMouseMove(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();
this.tl.to(intersects[i].object.scale, 1, {
x: 2,
ease: Expo.easeOut
});
}
}
render();
window.addEventListener('mousemove', onMouseMove);
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/102/three.js"></script>
My attempts to use an If Statement on the 'intersects' index 0 to control the scale increase and decrease have been unsuccessful. I have also tried adapting code from online sources but have not achieved the desired results. Any assistance, including links to tutorials on If statement usage in threejs, would be greatly appreciated.