Search code examples
babylonjs

How to update BabylonJS scene after changing some JS variables?


We can render a scene in Babylon.JS reading values like position/scale from form fields. But does it allow to make changes in scene listening real time changes in input fields like $('input').val().

var cusotm_position = $('input').val();
canvas = document.getElementById("renderCanvas");
engine = new BABYLON.Engine(canvas, true);
scene = createScene(); //draws a mesh at custom_position 
engine.runRenderLoop(function () {
    scene.render();
});

$("input").change(function(){
    cusotm_position = $('input').val();
    scene.render();//doesn't seem to be updating the mesh to new value of custom_position
});

I tried to call scene.render(); on event listener of change in input but that doesn't seem to be doing anything. Is there anything like refrest/update to change to updated variable values. Better if this can be done without removing everything and recreating fresh scene.


Solution

  • Calling .computeWorldMatrix() method of BABYLON.AbstractMesh object (and thus any Mesh) does just what it says on the tin - forces recomputing of the object's transform matrix.

    But the actual problem seems to be that your code is not doing what you think it is doing. This point:

    scene = createScene(); //draws a mesh at custom_position

    Since you are later calling .render() on that same scene object, your createScene() function returns your main scene , and it seems the only place where you assign a position to your mesh (by the way, you would do well to provide the code for that function in your question, since at this point I'm not sure it actually does any of that). So unless you call it every frame (and since I'm not seeing it called in the render loop, I'm gonna assume you don't), you are never assigning that value to your mesh.

    What you need to do is:

    1) Get a reference to your mesh. It can be done like this: var your_mesh = scene.getMeshById("your_mesh_id");

    2) Get your position as a BABYLON.Vector3: var custom_position = new BABYLON.Vector3(value_for_x, value_for_y, value_for_z);

    3) Assign position to mesh: your_mesh.position = custom_position;

    At this point, you shouldn't need anything more than the scene.render() called in render loop.