オブジェクトなどをマウスなどで選択できる仕組みを提供します。
初期状態では無効化されています。
connect() を呼び出すことで有効化されます。
raycaster.connect()connect の引数で、各種の設定を行うことができます。
無効化する場合は、disconnect() を呼び出します。
raycaster.disconnect()まず、init() の戻り値から raycaster を取得します。
const { create, camera, controls, animate, raycaster } = init();その後、connect() を呼び出すことで有効化されます。
raycaster.connect()animate() 内で raycaster.getIntersections(対象) を呼び出すことで、マウスが指しているオブジェクトを取得することができます。
const intersections = raycaster.getIntersections([cube1, cube2])intersections は配列で返され、マウスが指しているオブジェクトが複数ある場合は、近い順に並んでいます。
なお、子オブジェクトを無視したい の場合は、オプション引数で recursive を false にすることで、子オブジェクトを無視することができます。
const intersections = raycaster.getIntersections([cube1, cube2], { recursive: false })intersections の各要素は、THREE.Intersection 型のオブジェクトです。
そのため、intersections[0].object で、交差しているオブジェクトを取得することができます。
const hit = intersections[0];
hit.object.position.set(0, 1, 0);
hit.object.material.color.set(0xff0000);const { camera, create, animate, controls, raycaster } = init();
camera.position.set(0, 0, 3);
controls.connect();
create.ambientLight();
create.directionalLight();
// レイキャスターを有効化
raycaster.connect();
const cube1 = create.cube({
position: [1, 0, 0],
});
const cube2 = create.cube({
position: [-1, 0, 0],
});
animate(({ delta }) => {
cube1.rotation.y += delta;
cube2.rotation.y += delta;
// レイキャスターで交差判定を行い、その結果を配列で取得
const intersections = raycaster.getIntersections([cube1, cube2])
// 結果を元に、交差しているオブジェクトの色を赤に変更
cube1.material.color.set(0xffffff);
cube2.material.color.set(0xffffff);
if (intersections.length > 0) {
intersections[0].object.material.color.set(0xff0000);
}
});