gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:55:41 26 4
gpt4 key购买 nike

代码正在执行它应该做的事情,但我在控制台中收到 2 个错误:“无法读取未定义的属性‘旋转’”。由于这两个变量被定义为全局变量,因此对它抛出错误的原因感到困惑。我错过了什么吗? (使用 TextureLoader(),因为 ImageUtils.loadTexture() 已被弃用)。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js</title>
<style>
body{
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r80/three.js"></script>
<script src="js/OrbitControls.js"></script>
<script>

//GLOBAL VARIABLES
var scene, camera, renderer, cameraControl, earthMesh, cloudMesh;

function init(){

//scene
scene = new THREE.Scene();

//renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor('#000', 1.0);
renderer.shadowMap.enabled = true;

//camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 1000);
camera.position.x = 35;
camera.position.y = 36;
camera.position.z = 33;
camera.lookAt(scene.position);

//earth mesh
var sphereGeometry = new THREE.SphereGeometry(10, 60, 60);
var sphereMaterial;
var sphereMaterialLoader = new THREE.TextureLoader();
sphereMaterialLoader.load(
'images/earth.jpg',
function(earthImage){
sphereMaterial = new THREE.MeshBasicMaterial({
map: earthImage
});
earthMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
earthMesh.name = 'earth';
scene.add(earthMesh);
render();
}
);

//cloud mesh
var cloudGeometry = new THREE.SphereGeometry(sphereGeometry.parameters.radius * 1.02,
sphereGeometry.parameters.widthSegments, sphereGeometry.parameters.heightSegments);
var cloudMaterial;
var cloudMaterialLoader = new THREE.TextureLoader();
cloudMaterialLoader.load(
'images/clouds.png',
function(cloudImage){
cloudMaterial = new THREE.MeshBasicMaterial({
map: cloudImage
});
cloudMaterial.transparent = true;
cloudMesh = new THREE.Mesh(cloudGeometry, cloudMaterial);
cloudMesh.name = 'cloud';
scene.add(cloudMesh);
render();
}
);

//camera control
cameraControl = new THREE.OrbitControls(camera);

document.body.appendChild(renderer.domElement);
render();
}

function render(){
renderer.render(scene, camera);
earthMesh.rotation.y += -0.001;
cloudMesh.rotation.y += 0.0005;
cameraControl.update();
requestAnimationFrame(render);
}

//initialize scene/render
window.onload = init;

</script>
</body>
</html>

最佳答案

看起来 earthMesh 正在您的 cloudMaterialLoader.load() 函数中异步初始化——您需要小心,因为当您第一次调用 render() earthMesh 时可能尚未加载,在这种情况下它仍将是未定义的。

处理此问题的几种方法是在加载 earthMesh 之前不调用 render(),或者检查 earthMesh 是否已在 render() 调用中加载,或任何您想象的事情。

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

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