正如你在下面看到的,我在场景中添加了一个网格,但每当我尝试缩放它或设置位置时,我都会得到一个网格为空的错误。
mesh2.position.set(0,0,-5);
mesh2.scale.set(0.2, 0.3, 0.2);
未捕获的TypeError:无法读取null的属性“position”
查看请帮助,因为我浪费了几个小时试图让它发挥作用。
function init()
{
var scene = new THREE.Scene();//CREATE NEW THREE JS SCENE
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var renderer = new THREE.WebGLRenderer({antialias:true}); //INIT NEW THREE JS RENDERER
renderer.setPixelRatio( window.devicePixelRatio ); //SET PIXEL RATIO FOR MOBILE DEVICES
renderer.setClearColor(new THREE.Color('#005b96'), 1) //SET BG COLOR
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); // SET SIZE
document.body.appendChild( renderer.domElement ); //APPLY CANVAS TO BODY
renderer.domElement.id = "canvas_threeJS";//ADD ID TO CANVAS
//ADD CAMERA TO THE SCENE
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR =1000;
var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(0,3,8); //SET CAMERA POSITION
camera.lookAt(new THREE.Vector3(0,0,-5));
scene.add(camera);
//ADD AMBIENT LIGHT
var ambientLight = new THREE.AmbientLight("#6497b1");
scene.add(ambientLight);
//HANDLE WINDOW RESIZE
//ADD MAIN LIGHT
var light = new THREE.PointLight("#b3cde0",.6);
light.position.set(-5,13,-1);
scene.add(light);
var mesh2 = null;
var loader = new THREE.JSONLoader();
loader.load('assets/models/spaceship001.json', function(geometry) {
mesh2 = new THREE.Mesh(geometry);
scene.add(mesh2);
console.log("done loading model");
});
mesh2.position.set(0,0,-5);
// mesh2.scale.set(0.2, 0.3, 0.2);
//START POSITION OF A LEVEL GROUP
var levelSpawn = -100;
//GET VISIBLE WIDTH AT levelSpawn POSITION
var vFOV = camera.fov * Math.PI / 180; // convert vertical fov to radians
var height = 2 * Math.tan( vFOV / 2 )*levelSpawn; // visible height
var aspect = window.innerWidth / window.innerHeight;
var width = height * aspect;// visible width
//START RENDER
update();
function update()
{
//UPDATE 3D SCENE
renderer.render( scene, camera );
//KEEP RENDERING
requestAnimationFrame( update );
}
}
答案 0 :(得分:2)
问题是javascript是一种异步语言。根据您的背景,您应该阅读。尝试将console.log("setting scale and postion")
放在这两行之下或之上。你会注意到,在加载网格之前,位置和比例设置为。
您需要做的是在传递给加载函数的回调函数内设置位置和比例,就在console.log("done loading model");
行下面。
您还可以阅读javascript Promises以更好地理解它。