I have recently started working with Three.js and I'm facing an issue with raycasting not detecting certain parts of a rotated mesh object. For instance, in the image below, when the mouse is at the position of the green circle, it's detected as being on the box and intersectObjects returns an array with that box. However, when the mouse is at the position of the red circle, it does not behave like it's on the box and intersectObjects returns an empty array.
https://i.sstatic.net/wmd8f.png
import * as THREE from 'three'
import { Mesh, MeshLambertMaterial } from 'three';
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, .1, 1000);
camera.position.z = 5;
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor("#e5e5e5");
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var raycaser = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var geometry = new THREE.BoxGeometry(3.5, .5, 3);
var material = new THREE.MeshLambertMaterial({ color: 0xFFCC00 });
var mesh = new THREE.Mesh(geometry, material);
mesh.rotation.set(.5, .8, 0);
scene.add(mesh);
var light = new THREE.PointLight(0xFFFFFF, 1, 500);
light.position.set(0, 1, 7);
scene.add(light);
var render = function () {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
render();
document.body.addEventListener("mousemove", (event) => {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = (event.clientY / window.innerHeight) * 2 - 1;
raycaser.setFromCamera(mouse, camera);
var intersects = Array.from(raycaser.intersectObjects(scene.children, true)).map(inter => inter.object as Mesh);
document.body.style.cursor = intersects.length > 0 ? "pointer" : "default";;
for (var i = 0; i < scene.children.length - 1; i++) {
var object = scene.children[i] as Mesh;
var material = object.material as MeshLambertMaterial;
material.emissive.set(intersects.includes(object) ? 0x666666 : 0x000000);
}
});
It could be related to the object rotation causing the issue. How can I ensure the correct behavior of Raycaster?