Three.js#01#入门

环境搭建

根据官方教程搭建开发环境。

项目根目录有index.html、main.js、public/三个文件(夹)

然后把nodejs16x卸载了,因为官方貌似今年底即将停止维护,换成了nodejs18x并且设置镜像:

npm install -g cnpm --registry=https://registry.npmmirror.com
npm config set registry https://registry.npm.taobao.org

这样有时候npm不好使可以试下cnpm,第二条指令好像可以解决npx速度慢的问题。继续遵循教程:

# three.js
npm install --save three

# vite
npm install --save-dev vite

然后通过npx vite把项目跑起来。

项目写好之后可以通过npx vite build打包。

基本概念和参数

遵循教程的第一段代码:

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

首先讲PerspectiveCamera的构造函数。

PerspectiveCamera构造函数的第一个参数是FOV(the field of view)视野,单位是度。决定可以看到的场景范围。FOV值越大,相机拍摄的范围就越广,场景看起来就更小,反之亦然。

第二个是纵横比。您几乎总是希望使用元素的宽度除以高度,否则您将得到与在宽屏电视上播放老电影时相同的结果-图像看起来被压扁了。

接下来是近裁剪面和远裁剪面(near and far clipping plane): 它们是用来控制渲染的范围的。这意味着,距离相机远于far值或近于near值的物体将不会被渲染。你现在不必担心这个,但你可能想在你的应用程序中使用其他值来获得更好的性能。

Next up is the renderer. In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It's a good idea to use the width and height of the area we want to fill with our app - in this case, the width and height of the browser window. For performance intensive apps, you can also give setSize smaller values, like window. innerWidth/2 and window. innerHeight/2, which will make the app render at quarter size.

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

我们需要的第三个东西是Mesh。Mesh是一个对象,它采用一个几何图形,并应用一个材质,然后我们可以将其插入到我们的场景中,并自由移动。

默认情况下,当我们调用scene.add()时,我们添加的东西将被添加到座标(0,0,0)中。这将导致相机和立方体都在对方的内部。为了避免这种情况,我们简单地将相机移出一点。

如果将上面的代码复制到我们前面创建的HTML文件中,您将看不到任何内容。这是因为我们实际上还没有渲染任何东西。为此,我们需要所谓的渲染或动画循环。

function animate() {
	requestAnimationFrame( animate );
	renderer.render( scene, camera );
}
animate();

这将创建一个循环,导致渲染器在每次屏幕刷新时绘制场景(在典型的屏幕上,这意味着每秒60次)。如果你是在浏览器中编写游戏的新手,你可能会说“为什么我们不直接创建一个setInterval呢?”事实上,我们可以这样做,但是requestAnimationFrame有很多优点。也许最重要的一点是,当用户导航到另一个浏览器选项卡时它会暂停因此不会浪费他们宝贵的处理能力和电池寿命。

Loading-3D-models

https://threejs.org/docs/index.html#manual/en/introduction/Loading-3D-models

Libraries and Plugins

https://threejs.org/docs/index.html#manual/en/introduction/Libraries-and-Plugins

Useful links

https://threejs.org/docs/index.html#manual/en/introduction/Useful-links

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章