這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助
前段時間接觸了Three.js后,試著用他加載了一些模型three.js初體驗簡陋的了解了一下three.js的相關使用,并且寫下了第一篇文章,但是過后還是對很多一知半解,作為不會建模且目前沒有接觸到相關業務需求的開發,難道沒有模型就什么都不會了嗎?因此我覺得有必要來試試沒有模型的情況下自己來構建場景,以便于加深理解,
我在前端干工地,最后成果如下圖,預覽地址

從圖中可以看到,整個畫面由以下構成
- 地面
- 房子
- 天空 下面就能一步步的構建這個場景,
一、 準備作業
我這里的環境是vue3 + vite,基本環境準備好后就要安裝three.js的庫,安裝完成后就可以繼續了,接下來搭建頁面的基本結構
<template>
<div >
<canvas
id="draw"
style="border: 1px solid; background-color: #000"
></canvas>
</div>
</template>
<script setup >
import * as THREE from "three";
import { onMounted } from "vue";
import { OrbitControls } from "@/controls/OrbitControls";//引入軌道控制器
//canvas的大小
const width = 500;
const height = 500;
//建筑的長寬
const baseWidth = 40;
const baseLength = 60;
let scene = null; //場景
let camera = null; //相機
let canvas = null; //用作渲染的canvas
let renderer = null; //渲染器
const group = new THREE.Group();//用于將建筑物的各個零件組合起來
onMounted(()=>{
//***一些代碼
})
</script>
由于要將影像顯示到頁面中的canvas中,因此需要在onMounted生命周期內獲取,接下來創建一下構建場景的幾個要素:相機(camera)、場景(scene)、渲染器(renderer)、燈光(light), 在onMounted中添加如下代碼:
canvas = document.querySelector("#draw");
//創建場景
scene = new THREE.Scene();
//創建一個透視相機
camera = new THREE.PerspectiveCamera(125, width / height, 1, 2000);
//設定相機位置
camera.position.set(-30, 30, 50);
//創建環境光
const hjLight = new THREE.AmbientLight(0xffffff);
//添加環境光至場景
scene.add(hjLight);
//添加房子的group到場景中
scene.add(group);
//添加軌道控制器
const controls = new OrbitControls(camera, canvas);
//渲染器
renderer = new THREE.WebGLRenderer({
canvas,//傳入要渲染的canvas,相關引數可以看檔案
antialias: true,//抗鋸齒
alpha: true,
});
//設定渲染器大小
renderer.setSize(width, height);
//渲染器開始渲染
renderer.render(scene, camera);
//執行
function animate() {
controls.update();
renderer.render(scene, camera);
}
animate()
通過以上代碼,幾要素我們已經具有,下面可以正式開始了,
二、創建地面
地面這里使用了three.js內置的CircleGeometry幾何體,這里沒有什么強制需求,符合樣子就可以, 下面添加一個方法createGround如下,隨便找一張圖片當作地面的材質,隨后呼叫,然后便可以看見一個半徑為500的圓形地面
//創建地面
function createGround() {
//匯入材質
const groundTexture = new THREE.TextureLoader().load("/grass.webp");
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set(100, 100);
const ground = new THREE.CircleGeometry(500, 100);
const groundMaterial = new THREE.MeshLambertMaterial({
side: THREE.DoubleSide,
map: groundTexture,
// transparent: true,
// opacity: 0.2,
});
const groundMesh = new THREE.Mesh(ground, groundMaterial);
groundMesh.name = "地面";//設定name屬性
groundMesh.rotateX(-Math.PI / 2);//旋轉用于呈現一個水平的地面
scene.add(groundMesh);
調整角度和大小后便能看到如下圖所示:

三、 開始創建房子
1、創建地板
在這里創建地板,這里使用的是內置的BoxGeometry幾何體,添加createFloor方法,如下:
//創建地板,可以理解為地基
function createFloor() {
const texture = new THREE.TextureLoader().load("/img/wood.jpg");
//設定地板大小,由于后面將要生成墻體存在設定為1的厚度,因此這里對地板的x,z均-2
const floor = new THREE.BoxGeometry(baseWidth - 2, 1, baseLength - 2);
const material = new THREE.MeshPhongMaterial({ map: texture });
const mesh = new THREE.Mesh(floor, material);
mesh.position.set(0, 1, 0);
mesh.name = "地板";
group.add(mesh);
}
呼叫上面的方法后頁面中如下圖

2、創建左右兩邊的墻體
這里開始左右兩邊的規則墻體,使用的也是內置的BoxGeometry幾何體,添加 createWall方法,這個方法回傳創建的墻體
function createWall() {
const wallTexture = new THREE.TextureLoader().load("/img/wall1.jpg");
const wall = new THREE.BoxGeometry(baseLength, 20, 1);
const wallMaterial = new THREE.MeshPhongMaterial({
map: wallTexture,
});
//墻體的網格
const wallMesh = new THREE.Mesh(wall, wallMaterial);
return wallMesh;
}
接下來呼叫方法生成第一面墻
let leftWall = createWall() leftWall.name = '左側的墻' group.add(leftWall)
呼叫后畫面中應該如下圖

很顯然這與我們的預期不符,下面設定墻體的位置并且讓左側的墻旋轉90度,注意rotateY的引數為弧度,
leftWall.rotateY(Math.PI / 2); leftWall.position.set(-baseWidth / 2, 10, 0);
調整完成后如下圖

接下來我們如法炮制右側的墻,可以重新呼叫一次方法或者使用幾何體物件三的clone方法,這里使用clone
const rightWall = leftWall.clone(); rightWall.position.set(baseWidth / 2, 10, 0); rightWall.name = "右側的墻"; group.add(rightWall);
調整后如下圖

3、創建前后的墻體

規則的,這個時候使用創建前面墻的幾何體便不行了,查閱檔案后得知可以使用擠壓緩沖幾何體(ExtrudeGeometry),官網的描述如圖

如何使用呢,構造器

檔案中清晰的表明了這個類有兩個引數,一個是 形狀或者包含形狀的陣列 和配置選項,那么到這里我產生了疑問,什么是形狀的陣列呢,接著查看檔案找到了shape這個類

實體代碼中一眼望去熟悉的api映入眼簾,因此大概能想象出用法, 由于前后兩堵墻大致的形狀都是相同的,因此寫一個回傳形狀陣列的方法 genwallShape
function genwallShape() {
const shape = new THREE.Shape();
let height = 20;//墻的高度
shape.moveTo(0, 0); //起點
shape.lineTo(0, height); //墻體高度
shape.lineTo(baseWidth / 2 - 1, height + 5); //墻體頂點
shape.lineTo(baseWidth / 2 - 1, height + 6); //墻體頂點
shape.lineTo(baseWidth / 2 + 1, height + 6); //墻體頂點
shape.lineTo(baseWidth / 2 + 1, height + 5); //墻體頂點
shape.lineTo(baseWidth, height);
shape.lineTo(baseWidth, 0);
shape.lineTo(0, 0);
return { shape };
}
生成點的陣列的的方法有了,接下來寫一個生成不規則墻體的方法createIrregularWall
//創建不規則墻體
function createIrregularWall(shape, position) {
const extrudeSettings = {
depth: 1,//定義深度,由于擠壓幾何體的點位都是x,y坐標組成的二位平面,這個引數定義向z軸的延展長度,即為墻的厚度
bevelEnabled: false,
};
const wallTexture = new THREE.TextureLoader().load("/img/wall1.jpg");
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
wallTexture.wrapS = wallTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set(0.05, 0.05);
const material = new THREE.MeshPhongMaterial({ map: wallTexture });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
group.add(mesh);
return mesh;
}
點位有了、方法也有了,下面開始創建后墻,添加一個對應的方法
//創建不帶門的不規則墻體
function createNoDoorWall() {
let { shape } = genwallShape();
let mesh = createIrregularWall(shape, [-baseWidth / 2, 0, -baseLength / 2]);
mesh.name = "帶門的墻對面的墻";
}
呼叫后如圖

問題又來了,怎么在墻上打洞呢,還是在檔案中找到了答案

shape上有一個屬性表示了孔洞了,接下來就好辦了
function createDoorWall() {
let { shape } = genwallShape();
const door = new THREE.Path();
//門的位置
door.moveTo(baseWidth / 2 + 5, 0);
door.lineTo(baseWidth / 2 + 5, 16);
door.lineTo(baseWidth / 2 - 5, 16);
door.lineTo(baseWidth / 2 - 5, 0);
door.lineTo(baseWidth / 2 + 5, 0);
// 形狀上的孔洞
shape.holes.push(door);
let mesh = createIrregularWall(shape, [
-baseWidth / 2,
0,
baseLength / 2 - 1,
]);
mesh.name = "帶門的墻";
}
呼叫后如下

可以看到門的形狀已經出來了
4、創建屋頂
這里我們開始創建屋頂,首先求出屋頂的寬度,也就是我們要創建的幾何體的z軸的延展

function createRoof() {
//屋頂寬
let width = Math.sqrt((baseWidth / 2) ** 2 + 5 ** 2) + 5;//+5讓有一點屋檐的效果
const geometry = new THREE.BoxGeometry(baseLength + 2, width, 1);
const texture = new THREE.TextureLoader().load("/img/tile.jpg");
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(2, 2);
const material = new THREE.MeshPhongMaterial({ map: texture });
const mesh = new THREE.Mesh(geometry, material);
mesh.rotateZ(THREE.MathUtils.degToRad(75));
mesh.rotateY(-Math.PI / 2);
mesh.position.set(baseWidth / 3 - 1, 22, 0);
mesh.name = "右屋頂";
group.add(mesh);
return { roof: mesh, width };
}
方法執行后如下圖,我們有了一個右邊的屋頂

如法炮制,再來一個左邊的屋頂
let { roof, width } = createRoof();
return
let leftRoof = roof.clone();
leftRoof.rotateX(THREE.MathUtils.degToRad(30));
leftRoof.position.set(-baseWidth / 3 + 1, 22, 0);
leftRoof.name = "左屋頂";
group.add(leftRoof);
隨后可以在畫面中看到如下圖,我們的房子,哦不,準確的說是倉庫已經出來了,,,

5、創建門
然后我們開始創建門,門的創建也是用的內置的BoxGeometry幾何體, 添加一個createDoor方法,如下
function createDoor() {
//紋理貼圖
const texture = new THREE.TextureLoader().load("/img/door.jpg");
//門的大小、尺寸
const door = new THREE.BoxGeometry(10, 15, 0.5);
const material = new THREE.MeshPhongMaterial({
map: texture,
transparent: true,
opacity: 1,
});
const doorMesh = new THREE.Mesh(door, material);
doorMesh.name = "門";
doorMesh.position.x = 5;
group.add(doorGroup);
}
呼叫后即可看到原本的門洞中出現了一扇門,如下圖

6、為場景添加點擊
接下來我想做一點擊開門的效果,那么首先要獲取到滑鼠點擊了哪些物體,很巧的是three.js為我們提供了一個Raycaster類,用來檢測射線觸碰到了哪些物體, 添加如下代碼
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function onPointerMove(event) {
// 將滑鼠位置歸一化為設備坐標,x 和 y 方向的取值范圍是 (-1 to +1)
pointer.x = (event.clientX / width) * 2 - 1;
pointer.y = -(event.clientY / height) * 2 + 1;
}
然后為canva添加點擊事件監聽
canvas.addEventListener(
"click",
() => {
const intersects = raycaster.intersectObjects(scene.children);
console.log(intersects[0]);
console.log("點擊了", intersects[0]?.object?.name);
},
false
);
隨后我們點擊場景中,在控制臺中便能清晰的列印出我們所點擊的物體,說明:intersectObjects方法會回傳射線經過的所有物體組成的陣列,陣列的第0位為離點擊區域最近的物體,因此可以視為被點擊的物體,

現在已經知道點擊的是哪個物體,下面就來添加門的影片效果
7、添加關門、開門影片效果
調整一下對上節的方法,如下,匹配到點擊的物體是門的時候再來觸發,
canvas.addEventListener(
"click",
() => {
const intersects = raycaster.intersectObjects(scene.children);
console.log(intersects[0]);
console.log("點擊了", intersects[0]?.object?.name);
if (intersects[0]?.object?.name == "門") {
// console.log(intersects[0].object.parent.rotation.y);
let speed = 0.05;
//再次點擊關門
if (intersects[0].object.parent.rotation.y <= -2.5) {
// console.log("關門");
let a = setInterval(() => {
if (intersects[0].object.parent.rotation.y >= 0) {
intersects[0].object.parent.rotation.y = 0;
clearInterval(a);
return;
}
intersects[0].object.parent.rotation.y += speed;
}, 1000 / 60);
} else {
// console.log("開門");
let a = setInterval(() => {
if (intersects[0].object.parent.rotation.y <= -2.5) {
clearInterval(a);
return;
}
intersects[0].object.parent.rotation.y -= speed;
}, 1000 / 60);
}
}
},
false
);
這樣就能正確的運行了嗎?當然不,上述代碼中讓門以y軸做旋轉,但是在three.js中,物體的旋轉軸為物體的中心,因此我們需要改變一下門的旋轉軸,使之在視覺上呈現出以旋轉中心的改變,下面改造一下createDoor方法,如下,
//創建門
function createDoor() {
const texture = new THREE.TextureLoader().load("/img/door.jpg");
const door = new THREE.BoxGeometry(10, 15, 0.5);
const material = new THREE.MeshPhongMaterial({
map: texture,
transparent: true,
opacity: 1,
});
const doorMesh = new THREE.Mesh(door, material);
// doorMesh.rotateY(Math.PI / 2);
// doorMesh.position.set(-baseLength / 2, 7, 0);
doorMesh.name = "門";
//以下代碼做出了更改
const doorGroup = new THREE.Group();//添加一個門的父級
doorGroup.name = "門的包裹";
doorGroup.position.set(-5, 8, baseLength / 2);//通過父級來改變門的旋轉軸
//現在這個是相對于父級
doorMesh.position.x = 5;
doorGroup.add(doorMesh);
group.add(doorGroup);
return doorGroup;
}
改造完后點擊門,會發現門繞著預期的旋轉軸打開了,如下圖

四、創建天空盒
這里的天空盒非常的簡單,使用內置的SphereGeometry幾何體創建一個與地面半徑一致的圓,然后載入貼圖
//天空盒
function createSkyBox() {
const texture = new THREE.TextureLoader().load("/img/sky.jpg");
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
// texture.repeat.set(1, 1);
const skyBox = new THREE.SphereGeometry(500, 100, 100);
const material = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.BackSide,
});
const skyBoxMesh = new THREE.Mesh(skyBox, material);
scene.add(skyBoxMesh);
}
最終呈現出的效果如下圖

在最后你通過回圈多創建幾個房子,像這樣

或者查看檔案切換成第一人稱控制器在自己創建的場景中遨游,
本文轉載于:
https://juejin.cn/post/7200571354926858301
如果對您有所幫助,歡迎您點個關注,我會定時更新技術檔案,大家一起討論學習,一起進步,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/547838.html
標籤:其他

