Find intersection point with a terrain (created with height map)

Hello, I want to raycast into a terrain (a plane with height map), however, the intersection point is logged as is on a flat plane other than a terrain. Part of my code is as follows:

const disMap = new THREE.TextureLoader().load(heightMap)
const material = new THREE.MeshStandardMaterial({
   side: THREE.FrontSide,
   displacementMap: disMap,
   displacementScale: disScale
})


const terrainGeom = new THREE.PlaneGeometry(sizeX, sizeY, widthSeg, depthSeg);
const terrainMesh = new THREE.Mesh(terrainGeom, material);
scene.add(terrainMesh);

document.addEventListener('mousedown',onMouseClick);
function onMouseClick(evt) {

  var rayCaster = new THREE.Raycaster();
  var mousePosition = new THREE.Vector2();
  var canvas = renderer.domElement;
  var canvasPosition = canvas.getBoundingClientRect();

  evt.preventDefault();

  mousePosition.x = ((evt.clientX - canvasPosition.left) / canvas.width) * 2 - 1;
  mousePosition.y = -((evt.clientY - canvasPosition.top) / canvas.height) * 2 + 1;

  rayCaster.setFromCamera(mousePosition, camera);
  var intersects = rayCaster.intersectObjects(lineObject, true);

  if (intersects.length > 0)
       console.log(intersects[0].point);
}

The displacement map is processed in the GPU, until then the object is practically flat. The raycaster works in a much earlier stage, so it sees the object as flat.

Iā€™m not sure what is the best way to resolve this, but if I were you, I will modify the vertices in the plane in JS, before raycasting.

2 Likes

Have a look at this answer

2 Likes