I'm encountering an issue where I can't seem to change the color of a cube when someone hovers over it. I've simplified the code as much as possible.
<script>
var container;
var scene, camera, renderer, mouse, raycaster;
var grid_items = [];
init();
grid();
render();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 500, 800, 1300 );
camera.lookAt( new THREE.Vector3() );
// Lights
var ambientLight = new THREE.AmbientLight( 0x606060 );
scene.add( ambientLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.x = Math.random() - 0.5;
directionalLight.position.y = Math.random() - 0.5;
directionalLight.position.z = Math.random() - 0.5;
directionalLight.position.normalize();
scene.add( directionalLight );
var directionalLight = new THREE.DirectionalLight( 0x808080 );
directionalLight.position.x = Math.random() - 0.5;
directionalLight.position.y = Math.random() - 0.5;
directionalLight.position.z = Math.random() - 0.5;
directionalLight.position.normalize();
scene.add( directionalLight );
renderer = new THREE.CanvasRenderer();
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild(renderer.domElement);
window.addEventListener('mousemove', onDocumentMouseMove, false );
}
function grid(){
var geometry = new THREE.BoxGeometry(100, 100, 100);
var material = new THREE.MeshBasicMaterial({ color: 0x0000ff });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
grid_items.push(cube);
}
function onDocumentMouseMove(event) {
mouse.x = (event.clientX / renderer.domElement.width) * 2 - 1;
mouse.y = - (event.clientY / renderer.domElement.height) * 2 + 1;
console.log(mouse.x+"-"+mouse.y);
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(grid_items);
if (intersects.length > 0) {
for (var i = 0; i < intersects.length; i++) {
console.log("OBJECT "+intersects[i])
intersects[i].object.material.color.set(0xff0000);
}
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
render();
}
function render() {
renderer.render( scene, camera );
}