My approach involves creating cubes and rectangles on my scene with userData that initially have all 6 parameters set to "false". I then cast a ray from each face and if it intersects with another object's face, I set that specific face's parameter to "true". Everything functions correctly, however, I am facing an issue when trying to revert the parameter back to "false" if the ray no longer intersects with that face.
Snippet of my code:
box.userData.sides = {
0: false,
1: false,
2: false,
3: false,
4: false,
5: false
}
collision.push(box);
scene.add(box);
checkRaycast();
}
load(0, 0, 0, 'cube', 0, 0, 0);
function checkRaycast() {
var raycaster = new THREE.Raycaster();
var intersects = [];
for (let j = 0; j < collision.length; j++) {
var pos = collision[j].geometry.attributes.position;
var ori = new THREE.Vector3();
var dir = new THREE.Vector3();
var a = new THREE.Vector3(),
b = new THREE.Vector3(),
c = new THREE.Vector3(),
tri = new THREE.Triangle();
var index = collision[j].geometry.index;
var faces = index.count / 3;
scene.updateMatrixWorld()
for (let i = 0; i < faces; i++) {
a.fromBufferAttribute(pos, index.array[i * 3 + 0]);
b.fromBufferAttribute(pos, index.array[i * 3 + 1]);
c.fromBufferAttribute(pos, index.array[i * 3 + 2]);
a.set(a.x + collision[j].position.x, a.y + collision[j].position.y, a.z + collision[j].position.z);
b.set(b.x + collision[j].position.x, b.y + collision[j].position.y, b.z + collision[j].position.z);
c.set(c.x + collision[j].position.x, c.y + collision[j].position.y, c.z + collision[j].position.z);
tri.set(a, b, c);
tri.getMidpoint(ori);
tri.getNormal(dir);
raycaster.set(ori, dir);
intersects = raycaster.intersectObjects(collision, true);
//scene.add(new THREE.ArrowHelper(dir, ori, 500, 0xff0000));
if (intersects.length > 0) {
var intFace = Math.floor(intersects[0].faceIndex / 2);
if (intersects[0].distance > 0 && intersects[0].distance < 0.2) {
intersects[0].object.userData.sides[intFace] = true;
}
} // this works but with all sides. I need to check if ray don't intersect specific side more
else {
collision[j].userData.sides[0] = false;
collision[j].userData.sides[1] = false;
collision[j].userData.sides[2] = false;
collision[j].userData.sides[3] = false;
collision[j].userData.sides[4] = false;
collision[j].userData.sides[5] = false;
}
}
}
}
`