Universal Camera Position Lagging Behind?

Assuming I have something like this for WASD keys:

    this.universalCamera.keysUp = [];
    document.addEventListener('keydown', event => { if (event.code == 'KeyW') console.log(camera.position) });

// ...etc for other keys

If i tap W one time the position of the camera comes out as: {_x: 0, _y: 0, _z: 0} despite the camera moving forward in the _z direction. If i tap W again then the result finally updates to something like {_x: 0, _y: 0, _z: 1.76594}.

The same thing happens when changing directions. If I was to hold down W it will console log {_x: 0, _y: 0, _z: 0} where _z lags behind for one press and then finally it increases in value consistently, but if i suddenly tap A or D (left or right on the _x axis)…it does the same thing where it lags behind and then finally proceeds to update properly after a second A or D press. And it will actually update my _z value.

Any ideas why this could be happening?

This is because the DOM event “keydown” is triggered before Babylon.js updates the camera position. If you type scene.activeCamera.position in the console of the browser after pressing “W”, you will see that the camera position is updated on the first keystroke.

Makes sense. Do you know of a good way to do this after Babylon has updated the camera position. Basically I am trying to press W, move the camera one unit in the Z direction, get the updated position, send this data to my socket server so it can be broadcasted to everyone in real time. I have everything else in place so it’s just a matter of waiting until the camera position is updated after keydown (or using something different than the document event listeners)

You can use the Camera.onViewMatrixChangedObservable observable as a way to know that the camera has moved.

There’s also Camera.onAfterCheckInputsObservable but this one is called even if the camera did not move, so won’t be of any help in your case.


I guess I am wondering if there is straight forward way in babylon to setup keybinds that fire after the rendering and stuff takes place. I saw there is this: Interacting With Scenes | Babylon.js Documentation but when testsing it seems these also fire before the camera and things are updated

You can use the scene.onAfterRenderObservable observable, which is an observable which is notified after everything related to the scene (rendering included) has been processed (but it is not related to key events).

I don’t know exactly when the key events are raised in Babylon.js, as these happen asynchronously in the browser…

Seems you may reduce the amount of code for camera controls (and make it more universal, for example, when keyboard language is switched) like

    // Controls  WASD