Cannot add to scene after rendering THREE.js

℡╲_俬逩灬. 提交于 2020-01-13 23:59:49

问题


See example:

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

In newer versions of THREE.js, if I call render before adding additional objects to the scene, they will never be visible, even with additional calls to render. Is this expected behavior?

See full code:

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:


Actually, the cube is rendered black on a black background.

You are rendering the scene first with no lights, and then again after adding a light.

As stated in the Wiki article How to Update Things with WebGLRenderer, properties that can't be easily changed in runtime (once a material is rendered at least once) include the number and types of lights.

Add the light to the scene before the first render, and everything will work as expected.

If you must add the light after the first render, then you need to set

material.needsUpdate = true;

three.js r.68



来源:https://stackoverflow.com/questions/25497541/cannot-add-to-scene-after-rendering-three-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!