在babylon.js中渲染之前创建网格

时间:2018-05-08 13:54:04

标签: javascript babylonjs

我想在每次渲染之前创建新的网格,这里是我的代码(最小的演示):

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();
});

我期望的行为是创建一系列球体,每个球体position.x略高于前一球体。但是,渲染后场景中只有三个网格,如下所示:

结果

enter image description here

我想知道我的代码有什么问题,以及如何正确实现它?

顺便说一下,scene.removeMesh(mesh)mesh.dispose()之间有什么区别?

1 个答案:

答案 0 :(得分:1)

这是因为这句话。

newOne.position = head.position;

它只是复制一个引用。所以现在新的球体和蛇[0]共享一个相同的位置实例,所以所有新创建的球体共享一个相同的位置实例(通过持有位置参考),并位于相同的位置。