How can I raycast onto a heightmap properly?

I have been using THREE.Terrain to generate terrain in a scene. I need to raycast onto the heightmap generated by THREE.Terrain to properly make a player move across the world without walking into ‘walls’. This would also be required for future entities, interactive sections, and structures to generate properly. I have been using basic raycaster code, but all it proceeds to do is send the player to the position where the terrain was generated. Is there a way where the raycaster can be influenced by height maps?

var castFrom = new THREE.Vector3();
var castDirection = new THREE.Vector3(0,-1,0);
var raycaster = new THREE.Raycaster(camera.position.clone(), new THREE.Vector3(0, -1, 0));
castFrom.copy(camera.position);
castFrom.y += 1000;
raycaster.set(castFrom,castDirection);
var intersections = raycaster.intersectObjects( terrain );
if (intersections.length > 0){
camera.position.y = intersections[0].point.y+20;
}

Thanks for your help,
New Three.JS user

Does it work if you do this instead:

var intersections = raycaster.intersectObject( terrain, true );

Or how about intersectObject( terrain ) instead of intersectObjects( terrain )?

BTW, I recommend using raycaster.setFromCamera.

For raycasting on complex terrain, the default raycasting will give up fast. Structuring the height data in a max-quadtree will let you do intersection tests much faster.

2 Likes

I’ll try it soon.