Configure Three.js FlyControls for Flight Simulation

This guide explains how to implement and configure FlyControls in Three.js to achieve unrestricted 3D movement, mimicking a flight simulator. You will learn how to import the controller, initialize it with a camera, adjust key configuration settings like movement and roll speed, and update the controls within the animation loop for a seamless flying experience.

1. Import FlyControls

FlyControls is an add-on module and must be imported separately from the core Three.js library.

import * as THREE from 'three';
import { FlyControls } from 'three/addons/controls/FlyControls.js';

2. Initialize the Controls

To set up FlyControls, instantiate the class by passing your camera and the renderer’s DOM element as arguments. The DOM element is required to capture keyboard and mouse inputs.

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new FlyControls(camera, renderer.domElement);

3. Adjust Configuration Properties

FlyControls offers several properties to customize the flight dynamics. Configure these properties right after initialization:

controls.movementSpeed = 100; // Units per second
controls.rollSpeed = Math.PI / 24; // Radians per second
controls.autoForward = false;
controls.dragToLook = true; // Highly recommended for standard desktop displays

4. Implement the Update Loop

FlyControls requires a delta time (the time elapsed since the last frame) to calculate movement and rotation accurately, ensuring consistent behavior regardless of frame rate fluctuations.

Initialize a THREE.Clock and update the controls inside your animation loop:

const clock = new THREE.Clock();

function animate() {
    requestAnimationFrame(animate);

    // Get the elapsed time since the last frame
    const delta = clock.getDelta();

    // Update the controls
    controls.update(delta);

    renderer.render(scene, camera);
}

animate();

Default Keyboard Controls

Once configured, the flight controls map to the following default keyboard inputs: