Search code examples
javascriptbabylonjs

Changing color of material in babylon.js


I am just getting into babylon.js, but I can't seem to figure out, how would you change color of a material ?

My code currently is:

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

It looks aweful to me. As you can see i am defining fn inside the createScene which then allows me to modify it that way, however I believe that there should be a better way of doing it. I tried creating a function outside the createScene(), that would fetch the color, and then use that for materialSphere1.diffuseColor, however that did not work. So my question is: Is there any other (nicer) way to change a color of a material in babylon.js


Solution

  • Why not declaring your material outside of the callback? You can also use scene.materials to browse materials