Hi, this is a total newbie question (sorry) and will take 2 seconds to answer, but I’ve somehow been stuck on it for two days.
For some reason, my cube isn’t detected by the Raycaster example used in the https://threejs.org/docs/#api/en/core/Raycaster example and honestly i really cant figure it out.
heres the js code
import * as THREE from ‘./three.module.js’;
let camera, scene, renderer;
let geometry, material, cube;
let raycaster, mouse, intersects;
var xSpeed = 0.1;
var ySpeed = 0.1;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 1000 );
camera.position.z = 5;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xf0f0f0 );
geometry = new THREE.BoxGeometry( 1, 1, 1 );
material = new THREE.MeshLambertMaterial({color: 0xffffff});
cube = new THREE.Mesh( geometry, material );
scene.add( cube );
cube.position.x = 4;
var light = new THREE.PointLight(0xFFFFFFF, 1, 500);
light.position.set(10,0,25);
scene.add(light);
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
document.addEventListener("keydown", onDocumentKeyDown);
document.addEventListener("mousemove", onMouseMove);
}
function animate() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.02;
raycaster.setFromCamera( mouse, camera );
intersects = raycaster.intersectObjects( scene.children);
for ( var i = 0; i < intersects.length; i++ ) {
console.log(mouse);
intersects[ i ].object.material.color.setHex( 0xff0000 );
}
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
function onDocumentKeyDown(event) {
var keyCode = event.which;
if (keyCode == 87) {
cube.position.y += ySpeed;
} else if (keyCode == 83) {
cube.position.y -= ySpeed;
} else if (keyCode == 65) {
cube.position.x -= xSpeed;
} else if (keyCode == 68) {
cube.position.x += xSpeed;
} else if (keyCode == 32) {
cube.position.set(0, 0, 0);
}
};
function onMouseMove (event) {
mouse.x = ( event.clientX / window.innerWidth) * 2 - 1;
mouse.y = (event.clientY / window.innerHeight) * 2 + 1;
}