Im assuming i have a small issue with how im doing ray-casting, if anyone could help, it would be highly appreciated.
Im trying to use a ray-caster to get the distance between two mesh objects, and it works. but only for a limited range? in the code below it prints the distance in the console, but as soon as it moves further than about 0.8 units it doesn’t register a ray intersect and stops printing values?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="../build/three.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry( 0.5, 0.5, 0.5 );
const green_material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const blue_material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
const enemyCube = new THREE.Mesh( geometry, green_material );
const playerCube = new THREE.Mesh( geometry, blue_material );
playerCube.name = "target"
scene.add( enemyCube );
scene.add( playerCube );
playerCube.position.y = 0.6;
playerCube.position.x = -0.6;
const raycaster = new THREE.Raycaster();
const search = [];
const lag = 0.02
camera.position.z = 5;
function checkForTarget() {
raycaster.set(enemyCube.position, playerCube.position)
let intersections = raycaster.intersectObjects(scene.children)
try {
console.log(intersections[0].distance)
}
catch(e) {}
}
async function animate() {
playerCube.position.x += 0.005 //this is to show where and how the program fails
checkForTarget();
renderer.render( scene, camera );
requestAnimationFrame( animate );
}
animate();
</script>
</body>
</html>
Any help would be appreciated as to why it eventually stops printing the distance
thanks