As a beginner, I have implemented THREE pointer lock controls and perspective camera for my object. However, when adding both of them to the object, only one gets added based on which one was added first. I'm also facing difficulty in moving the object in the direction of the WASD keys along with rotating it as per the camera angle. Below are the important snippets of code.
The object moves correctly in the North, East, South, West directions, but if I move the camera, it still moves according to its initial direction rather than adjusting to the new angle. For example, if I aim East and move forward, the object goes North.
Additionally, whenever I move in any direction, the object snaps back to the position 0, 0, 0.
function e() {
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
var playerGeometry = new THREE.BoxBufferGeometry(10, 40, 10);
playerGeometry = playerGeometry.toNonIndexed(); // ensure each face has unique vertices
var playerMaterial = new THREE.MeshPhongMaterial({
specular: 0xffffff,
flatShading: true,
vertexColors: THREE.VertexColors
});
window.player = new THREE.Mesh(playerGeometry, playerMaterial);
console.log(player);
window.player.add(camera);
camera.position.set(0, 20, 20);
controls = new THREE.PointerLockControls(camera);
window.player.add(controls.getObject());
scene.add(player);
objects.push(player);
}
========================================================================= // Then the animation, these are just snippets not ofc the whole thing
function animate() {
requestAnimationFrame(animate);
if (controls.enabled) {
raycaster.setFromCamera(direction, camera);
var time = performance.now();
var delta = (time - prevTime) / 1000;
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
velocity.y -= 3.8 * 100.0 * delta; // 100.0 = mass
if (window.player.position) {
window.player.position.z = Number(keys[87]) - Number(keys[83]);
window.player.position.x = Number(keys[65]) - Number(keys[68]);
window.player.position.normalize(); // this ensures consistent movements in all directions
if (keys[87] || keys[83]) window.player.position.z -= window.player.position.z * 400.0 * delta;
if (keys[65] || keys[68]) window.player.position.x -= window.player.position.x * 400.0 * delta;
if (keys[32]) velocity.y = 200;
}
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;
if (camControls) camControls.update(delta);
}
renderer.render(scene, camera);
}