将球体颜色设置为three.js中坐标的函数

时间:2017-03-15 01:07:35

标签: javascript three.js

鉴于这个基本球体渲染在three.js中,如何修改它以使球体的颜色是球体上坐标的函数?例如,将球体的上半部分设为红色,将下半部分设为黑色?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 400);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);


camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);

    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
};

render();

2 个答案:

答案 0 :(得分:0)

例如,这种变化怎么样?

从“MeshNormalMaterial”更改为“MeshLambertMaterial”

添加环境光

添加聚光灯

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 400);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshLambertMaterial({color: 0xffffff});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Ambient light
var ambientLight = new THREE.AmbientLight( 0x707070);
// Spot light
var directionalLight = new THREE.DirectionalLight(0xff0000,0.8);
directionalLight.position.set(-60,60,0);
scene.add( ambientLight, directionalLight);

camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);

    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
};

render();

答案 1 :(得分:0)

作为一个选项,您可以检查球体面部法线的y坐标,如果它大于0,则表示面部位于上半部分,否则位于下半部分。

enter image description here

var sphereGeom = new THREE.SphereGeometry(5, 32, 24);
sphereGeom.faces.forEach(function(face){ // loop through faces
    if (face.normal.y > 0) // check y-coordinate of a face's normal
    face.color.setHex(0xFF0000); // set the color of the face (red)
    else
    face.color.setHex(0x000000); // set the color of the face (black)
})

var sphere = new THREE.Mesh(sphereGeom, new THREE.MeshStandardMaterial({
    vertexColors: THREE.FaceColors // use face colors
}));
scene.add(sphere);

jsfiddle示例。

但这是一个特例。对于更复杂的几何,您可以检查面的顶点坐标。像这样:geometry.vertices[face.a] - 这里我们找到了顶点数组中一个面的顶点坐标。