babylonjs

babylonjs - how do i move or scale an imported mesh out of its scope?


failed attempts

here are some forced attempts to do it, inside BABYLON.SceneLoader.ImportMesh...{ newMeshes[0].position.x=10; } it works using the local item newMeshes[0], but out of this nothing works.


Solution

  • This is because the variable newMeshes is only defined inside the callback function. If you want to get the variable outside of the function you need it to be defined in the global scope. To do this simply declare a variable before ImportMesh is called and inside of ImportMesh's callback function set that variable to newMeshes[0] like this:

    var meshisin = BABYLON.AbstractMesh;
    // Define the variable in the global scope.
    var skullMesh;
    meshisin = BABYLON.SceneLoader.ImportMesh("", "scenes/", "skull.babylon", scene, function (newMeshes) {
        skullMesh = newMeshes[0];
    });
    

    Then you can change the position of the mesh with: skullMesh.position.x = 10;.

    But since it takes say 1 second to load the mesh you delay using the mesh until it's loaded with a setTimeout like this:

    setTimeout(function() {
        skullMesh.position.x = 10;
    }, 1000);
    

    All in all your code would become:

    var meshisin = BABYLON.AbstractMesh;
    // Define the variable in the global scope.
    var skullMesh;
    meshisin = BABYLON.SceneLoader.ImportMesh("", "scenes/", "skull.babylon", scene, function (newMeshes) {
        skullMesh = newMeshes[0];
    });
    
    setTimeout(function() {
        skullMesh.position.x = 10;
    }, 1000);
    

    PS: It's generally not a good idea to post code in images.