Search code examples
javascriptbabylonjs

create mesh before render in babylon.js


I want to create new mesh before each render, here's my code(a minimal demo):

let canvas,
    engine,
    camera,
    scene;

function initEngine(){
    canvas = document.getElementById("renderCanvas");
    engine = new BABYLON.Engine(canvas, true);
}

function createScene(){
    initEngine();

    let scene = new BABYLON.Scene(engine);

    camera = new BABYLON.ArcRotateCamera("camera", Math.PI / 2, Math.PI / 2, 4, BABYLON.Vector3.Zero(), scene);
    camera.attachControl(canvas, true);


    let light1 = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0,1,0), scene);

    let ground = BABYLON.MeshBuilder.CreateGround(
        "ground",
        {
            width:30,
            height:30
        },
        scene
    );

    ground.position.y -= 0.5;

    let sphere1 = BABYLON.MeshBuilder.CreateSphere(
        "sphere1",
        {

        },
        scene
    );

    let sphere2 = sphere1.clone("sphere2");
    let sphere3 = sphere1.clone("sphere3");

    sphere1.position.z = -18;
    sphere2.position.z = -19;
    sphere3.position.z = -20;

    let snake = [
        sphere1,
        sphere2,
        sphere3
    ];

    (function(){
        let counter = 4;
        scene.registerBeforeRender(function(){
            let newOne = BABYLON.MeshBuilder.CreateSphere(
                "sphere" + counter,
                {

                },
                scene
            );
            let head = snake[0];
            newOne.position = head.position;
            newOne.position.x += 0.02;
            snake.unshift(newOne);
            ++counter;
        });
    })();

    window.addEventListener("resize", function(){
        engine.resize();
    });

    return scene;
}

scene = createScene();

engine.runRenderLoop(function(){
    // box.position.z += 0.01;
    scene.render();
});

My expecting behavior is to create a series of spheres, each position.x is slightly higher than the previous one. However, there are only three meshes in the scene after rendering, like this:

result

enter image description here

I want to know what is wrong with my code, and how to implement it properly?

By the way, what is the difference between scene.removeMesh(mesh) and mesh.dispose()?


Solution

  • It's because of this statement.

    newOne.position = head.position;
    

    It just copy a reference. so now the new sphere and snake[0] share a same position instance, so all the newly created spheres share a same position instance(by holding a position reference), and located in the same position.