I'm having trouble understanding why I keep getting this error message:
Cannot read property 'material' of undefined" at line " scene.getObjectByName("cube").material.opacity = control.opacity; "
This is my current code:
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();