I’m trying to use the PointerLockControl to move through a map terrain. I just copied the example and modified it like this:
if ( controls.isLocked === true && self.terrains ) {
raycaster.set(controls.getObject().position, new THREE.Vector3(0, -1, 0));
raycaster.ray.origin.y -= 10;
let intersects = raycaster.intersectObjects(self.terrains.children);
let onObject = intersects.length > 0;
let time = performance.now();
let delta = (time - prevTime) / 1000;
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass
direction.z = Number( moveForward ) - Number( moveBackward );
direction.x = Number( moveLeft ) - Number( moveRight );
direction.normalize(); // this ensures consistent movements in all directions
if (moveForward || moveBackward) velocity.z -= direction.z * 3200.0 * delta;
if (moveLeft || moveRight) velocity.x -= direction.x * 3200.0 * delta;
if (onObject === true) {
let hit = intersects[0];
console.log(hit);
velocity.y = Math.max(0, velocity.y);
canJump = true;
}
controls.getObject().translateX( velocity.x * delta );
controls.getObject().translateY( velocity.y * delta );
controls.getObject().translateZ( velocity.z * delta );
if (controls.getObject().position.y < 10) {
velocity.y = 0;
controls.getObject().position.y = 10;
canJump = true;
}
prevTime = time;
}
Unfortunately it doesn’t work. It keeps me at position.y = 10
. My terrain is a bit big its about pos.x = 19100; pos.z = -19100
from edge to edge. The height of the terrain also ranges between pos.y = 0; pos.y = 2000
.
I’ve also tried this:
if (onObject === true) {
let hit = intersects[0];
velocity.y = Math.max(hit.point.y, velocity.y);
canJump = true;
}
and if it does find an intersect the camera jitters up and down but sometimes it can’t even get an intersect even if there is a terrain below that is clearly intersecting.
Also sometimes the terrain is above the camera. So my idea was to cast a ray from above starting from the highest value for pos.y
going all the way down to infinity and the first terrain mesh I hit I take the y position and set my controls to that position. But I can’t seem to make it work like that. How do I do this correctly?
Lastly, doing the idea above will put the camera at exactly the floor view. I want it to make it look like the camera is eye level. How do I offset it to make it seem like a first person view? To note, I’ve tried pos.y += 60
and this seems to put the camera on the eye level but it still doesn’t really fix the ray casting.
Thank you