threejs, Keep object on surface of another object

javascript, three.js

Solution

The THREE.Raycaster should work indeed, as you already guessed.

In the update loop you need to cast rays downwards

var raycaster = new THREE.Raycaster();
raycaster.set(yourMovingObject.position, THREE.Vector3(0, -1, 0));

After that you will need to determine a distance from the ground where the object needs to stop 'falling'

var distance = 40; //set to your own measurements

And last but not least, check the intersections

var velocity = new THREE.Vector3();

var intersects = raycaster.intersectObject(floor); //use intersectObjects() to check the intersection on multiple

//new position is higher so you need to move you object upwards
if (distance > intersects[0].distance) {        
    yourMovingObject.position.y += (distance - intersects[0].distance) - 1; // the -1 is a fix for a shake effect I had
}

//gravity and prevent falling through floor
if (distance >= intersects[0].distance && velocity.y <= 0) {
    velocity.y = 0;
} else if (distance <= intersects[0].distance && velocity.y === 0) {
    velocity.y -= delta ;
}

yourMovingObject.translateY(velocity.y);

Something like this should work, but you will have to tweak it for your own environment.

Problem

I m generating a terrain geometry like this: ``` var geometry = new THREE.PlaneGeometry(100, 100, 100 , 100 ); for (var i = 0, l = geometry.vertices.length; i < l; i++) { geometry.vertices[i].z = Math.random() / 2; } geometry.computeFaceNormals(); floor = new THREE.Mesh(geometry, floorMaterial); ``` and have another object3d that is supposed to walk on the floor surface. how can i find out how much my object has to go up or down? maybe with raycaster. [Edited] well the the first part is solved, but the second part is that the distance that raycaster returns is not right, it s somehow flipped for each face. check the example: http://myhtmltest.net76.net/raycast.html

Original source