场景切换.gif
1、在已有的场景中再次新建一个场景loadingScreen
通过创建对象的方式去创建一个新的场景所需的属性
// 创建一个对象,用于存放加载场景所需的所有内容
let loadingScreen = {
scene: new THREE.Scene(),
camera: new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 100),
box: new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0x4444ff
})
)
}
2、设置一个资源加载器loadingManager
创建一个资源加载器,同时设置一个资源的加载状态值Resource_Load
// 创建一个加载管理器
let loadingManager = null;
// 资源是否加载完成
let Resource_Load = false;
3、设置新建的加载场景对象的一些属性
这个场景是针对新建的场景的一些相机、网格等的设置项,以及将箱子加到这个新的场景中去
// 设置加载场景对象的一些属性
loadingScreen.box.position.set(0, 0, 5);
loadingScreen.camera.lookAt(loadingScreen.box.position);
// 将网格箱子添加到新的场景中去
loadingScreen.scene.add(loadingScreen.box);
4、实例化加载器
接着去实例化加载器,资源加载分为两种状态,一是加载的过程中,另外一个是加载完成的状态。当资源加载完成时,就把加载的状态设置为true,表示资源已经加载完成。
// 实例化加载器
loadingManager = new THREE.LoadingManager();
// 加载过程
loadingManager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
}
// 加载完成
loadingManager.onLoad = function () {
Resource_Loader = true;
}
5、动画帧函数中判断资源是否加载完成
当资源加载未完成时,执行的是之前的scene
场景中的动画函数,当Resource_Loader
这个资源加载完成后为true,便开始执行新建的场景中的动画帧。
function animate() {
// 在加载资源时运行此块代码
console.log(Resource_Loader)
if (Resource_Loader) {
// 当资源加载完成时,执行新建的场景的动画,否则执行其他的场景的帧函数
requestAnimationFrame(animate);
loadingScreen.box.position.x -= 0.05;
if (loadingScreen.box.position.x < -10)
loadingScreen.box.position.x = 10;
loadingScreen.box.position.y = Math.sin(loadingScreen.box.position.x);
renderer.render(loadingScreen.scene, loadingScreen.camera);
return;
}
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render(scene, camera);
}