Search code examples
reactjscamerameshbabylonjs

How do I get the camera to focus on the object and keep it in center focus using Babylonjs?


What I really want is to put the mesh on the object and have the camera focus on that mesh. I think they do this with the lookAt function, but I don't know how to use it correctly.

I got help from this page : https://www.babylonjs-playground.com/#1CSVHO#12

I tried some function demos.

 setCamera_Mesh = () => {
        let { currentWidth, currentDepth, rowCount } = this.currentConfig;
        let sphere = Mesh.CreateSphere("sphere", 1, this.scene);
        let referenceBox = Mesh.CreateBox("referenceBox", { width: 1, height: 1, depth: 1, updatable: true });


        sphere.scaling = new Vector3(0.1, 0.1, 0.1);
        sphere.position = this.scene.cameras[0].position;
        sphere.parent = this.scene.cameras[0];

        this.referenceBox && this.referenceBox.dispose()

        referenceBox.position = new Vector3(0, 0, 0.08);

        referenceBox.enableEdgesRendering();
        referenceBox.edgesWidth = 1;
        referenceBox.edgesColor = new Color4(0, 0, 1, 0.05);
        referenceBox.visibility = 0.5;
        referenceBox.scaling = new Vector3(currentDepth / 40, rowCount / 3, currentWidth / 100);


        this.referenceBox = referenceBox;
        sphere.lookAt(referenceBox.position);
    }

Solution

  • I had to use setParent () instead of .parent where I added the camera as parent.

    When I edit the code as below, it worked correctly.

    setCameraToMesh = () => {
            let { currentWidth, currentDepth, rowCount } = this.currentConfig;
            let sphere = MeshBuilder.CreateSphere("referenceSphere", this.scene);
            let referenceBox = MeshBuilder.CreateBox("referenceBox", { width: 0.1, height: 0.1, depth: 0.1, updatable: true });
    
            sphere.scaling = new Vector3(0.1, 0.1, 0.1);
            sphere.position = this.scene.cameras[0].position;
            sphere.setParent(this.scene.cameras[0]);
            this.referenceBox && this.referenceBox.dispose()
    
            referenceBox.position = new Vector3(0, rowCount / 500, 0.08);
            referenceBox.enableEdgesRendering();
            referenceBox.edgesWidth = 1;
            referenceBox.edgesColor = new Color4(0, 0, 1, 0.05);
            referenceBox.visibility = 0.05;
            referenceBox.scaling = new Vector3(currentDepth / 40, rowCount / 3, currentWidth / 100);
    
            this.referenceBox = referenceBox;
    
            sphere.lookAt(referenceBox.absolutePosition);    
            this.scene.cameras[0].focusOn([referenceBox], true);
        }