我无法理解为什么它会向我显示以下错误:
无法阅读财产'材料'未定义"在线" scene.getObjectByName(" cube")。 material.opacity = control.opacity; "
我的代码:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
document.body.appendChild( renderer.domElement );
var axisHelper = new THREE.AxisHelper( 40);
scene.add( axisHelper );
var cubeGeometry = new THREE.CubeGeometry( 5, 5, 5 );
var cubeMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
cube.position.x = 0;
cube.position.y = 5;
cube.position.z = 0;
cube.castShadow= true;
scene.add( cube );
var planeGeometry = new THREE.PlaneGeometry( 50, 50, 50 )
var planeMaterial = new THREE.MeshLambertMaterial( { color: 0Xcccccc } );
var plane = new THREE.Mesh(planeGeometry,planeMaterial);
plane.receiveShadow = true;
plane.rotation.x=-0.5*Math.PI;
plane.position.x=0
plane.position.y=0
plane.position.z=0
scene.add( plane )
var ambientLight = new THREE.AmbientLight(0x0c0c0c);
scene.add(ambientLight);
var spotLight = new THREE.SpotLight( 0xffffff );
var lightHelper = new THREE.SpotLightHelper( spotLight );
spotLight.position.set( 10,50,20);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
//scene.add (lightHelper)
scene.add( spotLight );
camera.position.x = 20;
camera.position.y = 15;
camera.position.z = 20;
camera.lookAt(scene.position)
function addControlGui(controlObject){
var gui = new dat.GUI();
gui.add(controlObject,"rotationSpeed",-0.01, 0.01);
gui.add(controlObject,"opacity",0.1,1);
gui.addColor(controlObject,"color");
}
var control = new function(){
this.rotationSpeed =0.005 ;
this.opacity= 0.6;
this.color = cubeMaterial.color.getHex();
}
var render = function () { scene.getObjectByName("cube").material.opacity=control.opacity;
scene.getObjectByName("cube").material.color =new THREE.Color(control.color);
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
requestAnimationFrame( render );
renderer.render(scene, camera);
};
addControlGui(control);
render();
答案 0 :(得分:3)
方法.getObjectByName(string)
将查找Object3D
,其中name
属性是给定字符串。因此,虽然您的网格确实是一个立方体,但您仍需要定义一个名称,以便场景知道如何引用它。因此,将name
属性设置为"cube"
:
var cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
...
cube.name = "cube";
...
scene.add( cube );