wasd camera move a car threejs in javascript

Code Solution

Here's an example of how to move a car in Three.js using WASD keys to control the camera:

index.tsx
// Initialize Three.js scene, camera, renderer, and car object

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var car = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 0xff0000 }));
scene.add(car);

// Listen for keyboard events and update camera position accordingly

var keys = {
    KeyW: false, KeyA: false, KeyS: false, KeyD: false
};

document.addEventListener('keydown', function (event) {
    if (event.code in keys) {
        keys[event.code] = true;
    }
});

document.addEventListener('keyup', function (event) {
    if (event.code in keys) {
        keys[event.code] = false;
    }
});

var speed = 0.1;

function animate() {
    requestAnimationFrame(animate);

    if (keys.KeyW) { car.position.z -= speed; }
    if (keys.KeyA) { car.position.x -= speed; }
    if (keys.KeyS) { car.position.z += speed; }
    if (keys.KeyD) { car.position.x += speed; }

    camera.position.set(car.position.x, car.position.y + 3, car.position.z + 5);
    camera.lookAt(car.position);

    renderer.render(scene, camera);
}
animate();
1324 chars
49 lines

In this example, we first initialize the scene, camera, renderer, and car object. We then listen for keyboard events and update the camera position based on which keys are currently being pressed. Finally, we update the camera position and look-at direction based on the car's position and render the scene.

gistlibby LogSnag