Camera Locked Until 1st Click?

For some reason, the camera in this Playground example is locked (detached?) until you click on the first mesh. After that, the camera moves freely with mouse commands (attached to the canvas?), and you can continue to move the meshes around.

I’ve been using this line to start a scene with a freely moving camera:
camera.attachControl(canvas, true);

But adding it returns this error:
Line 16 : 981438 - Cannot read property ‘addEventListener’ of undefined

Any suggestions?

Thanks in advance :+1:

-Dustan

You need to use attachControl after you defined canvas. If you use it before it doesn’t know what canvas is and cannot attach eventListener to it.

3 Likes

Thanks! It works perfectly now :+1: In the interest of understanding why it works, is getRenderingCanvas a way to tell the program to look for what’s happening in any particular moment in time in the scene?

Thanks again!

-Dustan

When you create an engine instance you need provide it with the canvas element where the content will be rendered out.

const engine = new BABYLON.Engine(canvas, true)

That canvas of course is HTML5 element which you usually get with

const canvas = document.getElementById(‘canvas_id’)

So basically **engine.getRenderingCanvas()**method, gets an instance of that canvas provided to the engine and stores it into variable.

With that said, the reason why you need to put canvas.attachControl() method after is because canvas variable is not yet defined (undefined).

attachControl() -> to gain control over the scene with your mouse (or any other input) you need to attach event listeners to the canvas element, which this method does behind the scenes.

So if you try to attachControl() before you defined canvas you get that error

Cannot read property ‘addEventListener’ of undefined

OK, I understand that much better now, thanks for the explanation!

1 Like