gpt4 book ai didi

javascript - 无法读取未定义的 Three.js 的属性 'material'

转载 作者:行者123 更新时间:2023-11-29 10:35:26 25 4
gpt4 key购买 nike

我不明白为什么会显示以下错误:

Can not read property ' material ' of undefined " at line " 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();

最佳答案

.getObjectByName(string) 方法将查找 Object3D,其中它的 name 属性是给定的字符串。因此,虽然您的网格确实是一个立方体,但您仍然需要定义一个名称,以便场景知道如何引用它。所以将 name 属性设置为 "cube":

var cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
...
cube.name = "cube";
...
scene.add( cube );

关于javascript - 无法读取未定义的 Three.js 的属性 'material',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com