前言
该文章主要讲元宇宙虚拟空间的初始化,基本核心技术点,不多说,直接引入正题。
引入threejs,,在index.html,
<body>
<script src="build/sketchbook.min.js"></script>
<script>
const world = new Sketchbook.World('build/assets/world.glb');
</script>
</body>
引入弹窗库,后续一系列弹窗操作
import Swal from 'sweetalert2';
判断预览器是否支持webgl
if (!Detector.webgl)
{
Swal.fire({
icon: 'warning',
title: 'WebGL compatibility',
text: 'This browser doesn\'t seem to have the required WebGL capabilities. The application may not work correctly.',
footer: '<a href="https://get.webgl.org/" target="_blank">Click here for more information</a>',
showConfirmButton: false,
buttonsStyling: false
});
}
初始化渲染器,对threejs的renderer分别进行一系列操作,设置设备像素分辨比,设置尺寸大小,设置色调映射为:THREE.ACESFilmicToneMapping,色调贴图曝光为1,开启阴影,设置软阴影
this.renderer = new THREE.WebGLRenderer(); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.setSize(window.innerWidth, window.innerHeight); this.renderer.toneMapping = THREE.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.0; this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
初始化物理世界,对threejs的renderer分别进行一系列操作,首先是创建一个物理世界,设置重力加速度,改进碰撞体算法,提高碰撞体性能(SAPB算法有一个更好的性能,应用了扫描和剪枝的算法),添加解算器(主要是运用物体碰撞检测),解算器次数是越多越精确,但是性能会下降,这里设置的迭代次数为10,开启一个类似于阻力的效果,当物体移动非常缓慢,可以将其休眠,以提高性能,设置帧率为60,SAPBroadphase在多个步骤的任意轴上测试刚体。
this.physicsWorld = new CANNON.World(); this.physicsWorld.gravity.set(0, -9.81, 0); this.physicsWorld.broadphase = new CANNON.SAPBroadphase(this.physicsWorld); this.physicsWorld.solver.iterations = 10;
this.physicsWorld.allowSleep = true;
this.parallelPairs = [];
this.physicsFrameRate = 60;
this.physicsFrameTime = 1 / this.physicsFrameRate; this.physicsMaxPrediction = this.physicsFrameRate;
初始化加载的,页面HTML内容
this.generateHTML();
generateHTML里的内容
private generateHTML(): void
{
// Fonts
$('head').append('<link href="https://fonts.googleapis.com/css2?family=Alfa+Slab+One&display=swap" rel="stylesheet">');
$('head').append('<link href="https://fonts.googleapis.com/css2?family=Solway:wght@400;500;700&display=swap" rel="stylesheet">');
$('head').append('<link href="https://fonts.googleapis.com/css2?family=Cutive+Mono&display=swap" rel="stylesheet">');
// Loader
$(` <div id="loading-screen">
<div id="loading-screen-background"></div>
<h1 id="main-title" class="sb-font">Sketchbook 0.4</h1>
<div class="cubeWrap">
<div class="cube">
<div class="faces1"></div>
<div class="faces2"></div>
</div>
</div>
<div id="loading-text">Loading...</div>
</div>
`).appendTo('body');
// Canvas
document.body.appendChild(this.renderer.domElement);
this.renderer.domElement.id = 'canvas';
}
引入输入模块,该模块的主要功能是·角色的移动,和鼠标的操作移动
this.inputManager = new InputManager(this, this.renderer.domElement);