如何在 Babylon.js 中为形状着色?

max*_*ner 3 javascript babylonjs

我正在处理babylonjs-playground.com 上的“基本场景”示例尝试对球体的颜色进行简单的修改。

这是我的尝试,可以交互运行:

https://www.babylonjs-playground.com/#95BNBS

这是代码:

var createScene = function () {

    // The original example, without comments:
    var scene = new BABYLON.Scene(engine);
    var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
    camera.setTarget(BABYLON.Vector3.Zero());
    camera.attachControl(canvas, true);
    var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
    light.intensity = 0.7;
    var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
    sphere.position.y = 1;
    var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);

    // My attempt to color the sphere
    var material = new BABYLON.StandardMaterial(scene);
    material.alpha = 1;
    material.diffuseColor = new BABYLON.Color3(1,0,0);
    scene.material = material;

    return scene;

};
Run Code Online (Sandbox Code Playgroud)

我尝试将彩色材质添加到球体中没有效果。

我还尝试在球体对象上查找与颜色相关的属性:

Object.keys(sphere).filter((key) => return key.includes("Color") )
// => "outlineColor", "overlayColor", "_useVertexColors", "edgesColor"
Run Code Online (Sandbox Code Playgroud)

除了 之外_useVertexColors,所有这些似乎都是颜色对象,但更改它们没有效果:

sphere.overlayColor.g = 1;
sphere.outlineColor.g = 1;
sphere.edgesColor.g = 1;
Run Code Online (Sandbox Code Playgroud)

aug*_*aug 5

你已经很接近了。您正在正确设置颜色,diffuseColor但实际上并未将其专门添加到您的球体中。

您的球体对象存储在中sphere,因此您需要做的是将material您创建的设置为 onsphere而不是 on scene

// My attempt to color the sphere
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(1.0, 0.2, 0.7);
sphere.material = material; // <--
Run Code Online (Sandbox Code Playgroud)

请参阅本教程