渲染THREE.js后无法添加到场景中

时间:2014-08-26 03:24:50

标签: javascript three.js

参见示例:

http://jsfiddle.net/pehrlich/nm1tzLLm/2/

在较新版本的THREE.js中,如果在向场景添加其他对象之前调用渲染,即使有额外的渲染调用,它们也永远不可见。这是预期的行为吗?

查看完整代码:

var cube, cube2, geometry, light, material, renderer;

window.scene = new THREE.Scene();

window.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

geometry = new THREE.CubeGeometry(75, 75, 16);
material = new THREE.MeshPhongMaterial({
  color: 0x0000ff
});
cube = new THREE.Mesh(geometry, material);
cube.position.set(80, 0, -400);
scene.add(cube);

camera.position.fromArray([0, 160, 400]);
camera.lookAt(new THREE.Vector3(0, 0, 0));

light = new THREE.PointLight(0xffffff, 8, 1000);

// comment out this line ot bring back second cube:
renderer.render(scene, camera);

scene.add(light);

geometry = new THREE.CubeGeometry(75, 75, 16);
material = new THREE.MeshPhongMaterial({
  color: 0x0000ff
});
cube2 = new THREE.Mesh(geometry, material);
cube2.position.set(-80, 0, -400);
cube2.castShadow = true;

scene.add(cube2);

renderer.render(scene, camera);

1 个答案:

答案 0 :(得分:5)

实际上,立方体在黑色背景上呈现黑色。

您首先渲染场景时没有灯光,然后在添加灯光后再次渲染场景。

如Wiki文章How to Update Things with WebGLRenderer所述,在运行时无法轻易更改的属性(一旦材质至少呈现一次)包含灯光的数量和类型。

在第一次渲染之前将灯光添加到场景中,一切都将按预期工作。

如果必须在第一次渲染后添加灯光,则需要设置

material.needsUpdate = true;

three.js r.68