StrandedKitty
StrandedKitty

Reputation: 302

Terrain intersection performance

I create var geometry = new THREE.PlaneGeometry(512,512,255,255); then parse jpg heightmap and change verticles' positions to receive deformed plane. Than I cast ray from the sky to the ground in the animate() function to get intersection point:

var raycaster = new THREE.Raycaster( new THREE.Vector3(player.x, 100, player.z), new THREE.Vector3(0, -1, 0) );
var intersects = raycaster.intersectObject( ground, true );
if(intersects.length == 1) {
    mesh.position.set(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);
}

But FPS become very low (<20). I also tried to get y-position through the height map, but texture is only 256 x 256, so if I want to make mesh follow the terrain the y-coordinate is jerking.

Upvotes: 0

Views: 198

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138307

Try to calculate as few as possible directly in the loop. This also means that you should allocate the raycaster outside of the loop. And using the range might also help to speed up raycasting:

 const direction = new THREE.Vector3(0, -1, 0);
 const position = new THREE.Vector3(player.x, 100, player.z);

 const raycaster = new THREE.Raycaster(position, direction, 0, 200);

 let y = 0;
 let count = 0;

Then inside the loop just sometimes recalculate the height:

 if(count = (count + 1) % 10){
   position.set(player.x, 100, player.z);
   y = raycaster.intersectObject( ground, true );
 }

 mesh.position.set(player.x, y, player.z);

Upvotes: 1

Related Questions