2017-07-10 83 views
2

我剛進入babylon.js,但我似乎無法弄清楚,如何更改材質的顏色?更改babylon.js中材質的顏色

我的代碼目前是:

/* eslint-disable */ 
import * as BABYLON from 'babylonjs'; 


// Get the canvas element from our HTML above 
const canvas = document.getElementById("root"); 

// Load the BABYLON 3D engine 
const engine = new BABYLON.Engine(canvas, true); 
let fn; 
let mainColor = new BABYLON.Color3(1.0, 0.2, 0.7); 

setTimeout(() => { 
    mainColor = new BABYLON.Color3(0.3, 0.2, 0.2); 
    fn(); 
}, 2000); 

// This begins the creation of a function that we will 'call' just after it's built 
function createScene() { 

    // Now create a basic Babylon Scene object 
    const scene = new BABYLON.Scene(engine); 

    // Change the scene background color to green. 
    scene.clearColor = new BABYLON.Color4(0.5, 0.8, 0.6, 0.8); 

    // This creates and positions a free camera 
    const camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 30, new BABYLON.Vector3(0, 0, 0), scene); 

    // This targets the camera to scene origin 
    camera.setTarget(BABYLON.Vector3.Zero()); 

    // This attaches the camera to the canvas 
    camera.attachControl(canvas, false); 

    // This creates a light, aiming 0,1,0 - to the sky. 
    const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 1), scene); 

    // Dim the light a small amount 
    light.intensity = .5; 

    // Let's try our built-in 'sphere' shape. Params: name, subdivisions, size, scene 
    const sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene); 

    const materialSphere1 = new BABYLON.StandardMaterial("texture1", scene); 
    materialSphere1.alpha = 1; 
    materialSphere1.diffuseColor = mainColor; 

    sphere.material = materialSphere1; 
    sphere.position.y = 1; 
    // Move the sphere upward 1/2 its height 

    // Let's try our built-in 'ground' shape. Params: name, width, depth, subdivisions, scene 
    const ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene); 
    fn =() => { 
     materialSphere1.diffuseColor = mainColor; 
    } 
    // Leave this function 
    return scene; 

    }; // End of createScene function 
    const scene = createScene(); 
    engine.runRenderLoop(function() { 
    scene.render(); 
    }); 
    window.addEventListener("resize", function() { 
    engine.resize(); 
    }); 

它看起來aweful給我。正如你所看到的,我在createScene中定義了fn,然後我可以用這種方式修改它,但是我相信應該有更好的方法來做到這一點。我試圖在createScene()之外創建一個函數,它將獲取顏色,然後將其用於materialSphere1.diffuseColor,但這不起作用。所以我的問題是:是否有任何其他(更好)的方式來改變巴比倫材料的顏色.js

回答

1

爲什麼不在回調之外聲明你的材料? 您也可以使用scene.materials瀏覽素材

相關問題