Why my raycaster selects all the objects in the scene?

import './style.css'
import * as THREE from 'three'
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls.js"

const raycaster = new THREE.Raycaster()

const canvas = document.querySelector(".webgl")
//sizes
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight
}

//scene and camera
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45,sizes.width/sizes.height,0.1,1000)
camera.position.set(0,0,60)

//lights
const ambientLight = new THREE.AmbientLight(0xffffff)
scene.add(ambientLight)

//Meshes
const box = new THREE.Mesh(
  new THREE.BoxGeometry(10,10,10,10),
  new THREE.MeshStandardMaterial({
    color: 0xffffff
  })
)
const boxId = box.id
scene.add(box)

//helpers
const gridHelper = new THREE.GridHelper(50)
scene.add(gridHelper)

const axesHelper = new THREE.AxesHelper(50)
scene.add(axesHelper)

//renderer
const renderer = new THREE.WebGLRenderer({canvas})
renderer.setSize(sizes.width,sizes.height)
renderer.setPixelRatio(window.devicePixelRatio)
renderer.render(scene,camera)

const controls = new OrbitControls(camera,renderer.domElement)

//event listeners
const pointer = new THREE.Vector2()
window.addEventListener('mousemove', (e) => {
	pointer.x = ( e.clientX / sizes.width ) * 2 - 1;
	pointer.y = - ( e.clientY / sizes.height ) * 2 + 1;
})

window.addEventListener('resize', () => {
  sizes.width = window.innerWidth
  sizes.height = window.innerHeight

  camera.aspect = sizes.width/sizes.height
  camera.updateProjectionMatrix()
  renderer.setSize(sizes.width,sizes.height)
  renderer.render(scene,camera)
})

//animation loop
const clock = new THREE.Clock()
const animate = () =>{
  const elapsedTime = clock.getElapsedTime()
  window.requestAnimationFrame(animate)

  raycaster.setFromCamera( pointer, camera );
	const intersects = raycaster.intersectObjects( scene.children );
  console.log(intersects)

	for ( let i = 0; i < intersects.length; i ++ ) {
		intersects[ i ].object.material.color.set( 0xff0000 );
	}

  renderer.render(scene,camera)
}
animate()

Try change:

for ( let i = 0; i < intersects.length; i ++ ) {
		intersects[ i ].object.material.color.set( 0xff0000 );
	}

to this:
if ( intersects.length > 0 ) { intersects[0].object.material.color.set( 0xff0000 ); }

1 Like

Yeah what @Chaser_Code said ^… also your cubes are all on top of each other. Raycaster returns all the objects hit by the ray, in the order that they were hit, so you usually only want to process the first intersect in the list for selection purposes.