I have a question related to three.js editor: What would a script in three.js editor look like if a point (or spot) light and camera followed mouse movement? Similar to how it is on this page 601 Inc. Have a great day!
Something like this should do the trick (put either as light script or scene script):
const light = this; // NOTE If script is put into Scene, use scene.getObjectByName('PointLightName'); here instead
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(0.0, 0.0);
const target = light.position.clone();
function pointermove(event) {
// NOTE Update cursor position - assumes canvas is fullscreen
pointer.set(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
}
function update(event) {
// NOTE First update light position to follow the latest cursor position
// You can either .copy or .lerp, .lerp is a bit smoother
light.position.lerp(target, 0.1);
// NOTE Update raycasting
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(scene.children, true);
if (!hits.length) {
target.set(0.0, 0.0, 0.0);
return;
}
const { point, normal } = hits[0];
target.copy(point);
target.y += 1.5;
}
(docs)
2 Likes
I have another question. What adjustments need to be made to this code to make it work with an older version (r120)? I tried changing pointermove to mousemove, but it’s still not functioning. Thank you!