Rotate Universal camera with WASD keys

want to use WASD keys to rotate the universal camera in my scene.

saw this example code:

Trying to convert this example to typescript, totally unsuccessful, if anyone can help.

1 Like

cc @PolygonalSun

Hey @cosmos,
If you want to use WASD to rotate, I could see two approaches. Both will require starting by removing the initial keyboard input code:

// Assuming camera is the name of your camera asset
camera.inputs.remove(camera.inputs.attached.keyboard);

First approach: Manually rotate

// Create an instance of the DeviceSourceManager and modify the cameraRotation with each rendered frame
        const dsm = new BABYLON.DeviceSourceManager(scene.getEngine());
        dsm.onDeviceConnectedObservable.add((eventData) => {
            if (eventData.deviceType === BABYLON.DeviceType.Keyboard) {
                const keyboard = dsm.getDeviceSource(BABYLON.DeviceType.Keyboard);
                scene.beforeRender = () => {
                    const w = keyboard.getInput(87);
                    const a = keyboard.getInput(65);
                    const s = keyboard.getInput(83);
                    const d = keyboard.getInput(68);
                    const rotationalSpeed = 0.002;
                    if (w === 1) {
                        camera.cameraRotation.x -= rotationalSpeed;
                    }
                    if (a === 1) {
                        camera.cameraRotation.y -= rotationalSpeed;
                    }
                    if (s === 1) {
                        camera.cameraRotation.x  += rotationalSpeed;
                    }
                    if (d === 1) {
                        camera.cameraRotation.y += rotationalSpeed;
                    }
                };
            }
        });

There are many ways to do this but I’ve elected to use a DeviceSourceManager to grab the keyboard status and manually modify the camera’s rotation based on the active keys. Example PG: UniversalCamera Manual Rotation | Babylon.js Playground (babylonjs.com)

Second Approach: Custom Input (in Typescript):
Universal Camera Custom Keyboard Input | Babylon.js Playground (babylonjs.com)

I know that the UniversalCamera uses FreeCameraKeyboardInput for its camera movement and that it already has functionality to rotate right and left but not up and down. You might be able to extend this functionality and add the up/down rotation yourself. As I said, there are many ways to do this so hopefully this helps you to get started.

3 Likes