Find the objects that a line intersects in three.js

Currently, I’m working on a three.js project where I should select two boxes from a board and draw a straight line connecting them, then I must highlight all the boxes that the line intersects. My big question now is how to to find which boxes the line intersects?

Link for codepen: https://codepen.io/lucasbrodersen/pen/PoKMRQr

Basically, you can push ‘x’ and it will select the box you have your mouse placed on. Once you select two boxes it will draw a line. (In order for the ‘x’ keyboard command work in codepen you must click on the orange margin, no clue why)

Any help would be appreciated (piece of code, links, material suggestion, math formulas)

Update: I now added raycaster2 on the end of my code, however I’m getting an empty array from intersects2. Any idea? Position1 and Position2 are giving me the correct coordinates.

import * as THREE from 'https://cdn.skypack.dev/pin/three@v0.126.1-YUoA6uASRjHQlgwWiOso/mode=imports/optimized/three.js';
import { OrbitControls } from 'https://unpkg.com/three@0.126.1/examples/jsm/controls/OrbitControls.js';

var count = 0;
const scene = new THREE.Scene();
//console.log(OrbitControls)

const camera = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.1, 1000)
camera.position.set(0,0,30)
camera.lookAt(0,0,0)
//camera.rotation.x = 35
const renderer = new THREE.WebGLRenderer({antialias: true})
const raycaster = new THREE.Raycaster()


renderer.setSize(innerWidth, innerHeight)
document.body.appendChild(renderer.domElement)


//iniciando geometrias


export function onWindowResize () {
    camera.aspect = innerWidth / innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(innerWidth, innerHeight)
    renderer.render(scene, camera)
}
window.addEventListener('resize', onWindowResize)

//criando chess board
var board, cubeGeo, lightMaterial, darkMaterial;

cubeGeo = new THREE.BoxGeometry(1,1,0.1);
lightMaterial = new THREE.MeshBasicMaterial({color: 0xff7b33});
darkMaterial = new THREE.MeshBasicMaterial({color: 0x8a8fc5});

board = new THREE.Group();
var k = 0;
for (let x = -10; x < 11; x++){
    for (let z = -10; z < 11; z++) {
        if (z%2 == false){
            var cube;
            cube = new THREE.Mesh(cubeGeo, x % 2 == false ?lightMaterial : darkMaterial);
            cube.name= "cube"+ k;
        } else {
            cube = new THREE.Mesh(cubeGeo, x % 2 == false ?darkMaterial : lightMaterial);
            cube.name= "cube"+k;
        }
        cube.position.set(x,z,0);
        board.add(cube);
        k++;
    }
}

scene.add(board);
//console.log(board)
//fim chess board

//var t = scene.add(new THREE.GridHelper(40,40,0xff0000,0xff0000,))

//Inicio Axis
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
axesHelper.position.z = 1
//Fim Axis

//Inicio Orbit Controls
let controls
controls = new OrbitControls(camera, renderer.domElement);
controls.target = new THREE.Vector3(0, 0, 0);
controls.addEventListener('change', render);

//Creating mouse
const mouse = {
    x: undefined,
    y: undefined
}

function render(){
    renderer.render(scene, camera);

    
}


function animate() {
    requestAnimationFrame(animate)
    renderer.render(scene, camera)
    raycaster.setFromCamera(mouse, camera)
    const intersects = raycaster.intersectObject(board, true);
    
    if (intersects.length > 0 ){
        //console.log(intersects[0].object.name)
        

    }

}
function changeColor(cubo){
    cubo.object.material = cubo.object.material.clone();
    cubo.object.material.color.setHex(0xff0000);
}



addEventListener('mousemove', (event)=> {
    mouse.x = ( event.clientX/ innerWidth) * 2 - 1 ;
    mouse.y = -( event.clientY/ innerHeight) * 2 + 1;

})

document.addEventListener("keydown", onDocumentKeyDown, false); 
const coordinate1 = [];
const coordinate2 = [];
const position1 = []
const position2 = []
function onDocumentKeyDown(event,x1,x2,y1,y2) {
    var keyCode = event.which;
    raycaster.setFromCamera(mouse, camera)
    const intersects = raycaster.intersectObject(board, true);
    
    if (keyCode == 88 && count <2) {
        changeColor(intersects[0])
        //console.log(intersects)
        //console.log(intersects[0].object.name)
        if (count == 0) {
            x1 = (intersects[0].object.position.x)
            y1 = (intersects[0].object.position.y)
            console.log(intersects[0].object.position)
            coordinate1.push(x1,y1)
            position1.push(intersects[0].object.position)
            
        }
        else if (count == 1) {
            x2 = (intersects[0].object.position.x)
            y2 = (intersects[0].object.position.y)
            coordinate2.push(x2,y2)
            console.log(intersects[0].object.position)
            position2.push(intersects[0].object.position)
            
        }        
        count++;
       
        console.log(coordinate1[0])
        console.log(coordinate2[0])
        //console.log(count)
        if (count == 2) {
            var dx=coordinate2[0]-coordinate1[0];
            var dy=coordinate2[1]-coordinate1[1];
            var d=2*dy-dx;
            var incrE = 2*dy;
            var incrNE = 2*(dy-dx);
            var x = coordinate1[0];
            var y = coordinate1[1];
            const vertices = [];
            
            vertices.push(x, y, 0); //start pixel
            while (x1 < x2) {
                console.log("entrou")
                if(d<=0){      // Choose E
                    d+=incrE;
                    x++;
                } else{        // Choose NE

                    d+=incrNE;
                    x++;
                    y++;
                }
                vertices.push(x,y,0);
            }

            const lineFromPoints = [];
            lineFromPoints.push(new THREE.Vector3(coordinate1[0],coordinate1[1],1));
            lineFromPoints.push(new THREE.Vector3(coordinate2[0],coordinate2[1],1));
            
            const testLine = new THREE.BufferGeometry().setFromPoints( lineFromPoints );
            const blue = new THREE.LineBasicMaterial({ color: 0x2f24f4});
            const lineColored = new THREE.Line(testLine, blue);
            
            scene.add(lineColored);
            console.log("Linha Colorida:")
            console.log(lineColored)
            //console.log(lineColored.raycast)
            var raycaster2 = new THREE.Raycaster();
            var direction2 = new THREE.Vector3();
            var direction = []
            var dirx,diry,dirz;
            console.log(position2)
            console.log("test",position2[0].x)
            dirx = position2[0].x- position1[0].x
            diry = position2[0].y - position1[0].y
            dirz = position2[0].z- position1[0].z
            direction.push(dirx,diry,dirz)
            console.log("Direction:::", direction)
            console.log("Origin", position1[0])
            console.log("Destin", position2[0])
            console.log("Test Sub", direction2.subVectors(position2[0],position1[0]))
            //var far = new THREE.Vector3();
            raycaster2.set(position1[0], direction2.subVectors(position2[0],position1[0]));
            //raycaster2.far = far.subVectors(position1, position2).length();
            var intersects2;
            intersects2 = raycaster2.intersectObjects(board, true);
            renderer.render(scene, camera);
            console.log(raycaster2)
            console.log(intersects2)
      


        }
        
    }
    if(keyCode == 13) // mudar para barra de espaço
    window.location.reload();
};



animate()