前言:好多天没有更新了,因为最近在公司上班有点累,回家趴一下就睡着了,还有就是想稍微放松一下,玩点游戏啥的,好在今天抽空,更新一下这篇文章,这篇文章主要是讲解Three.js中的投射光线,以及如何与3维物体进行交互,话不多说,直接show my code.
基础代码
先将基础代码完成,顺便温习一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 300 );
camera.position.set(0, 0, 20);
scene.add(camera);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.physicallyCorrectLights = true;
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
function render() { controls.update(); renderer.render(scene, camera); requestAnimationFrame(render); }
render();
window.addEventListener("resize", () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); });
|
创建立方体
首先我们先创建一个立方体
1 2 3 4 5 6 7 8
| const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial();
const cube = new THREE.Mesh(cubeGeometry, material);
scene.add(cube);
|
生成1000个立方体
先将上文生成物体部分注释掉,再添加以下代码,生成1000立方的立方体
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
因为我们知道一个物体的位置是一个三维坐标,需要x,y,z三个值来确定,所以我们可以通过循环来生成1000个立方体,相当于是10*10*10的一个物体,如果需要让他们沿着轴对称,就需要-5,5之间来生成 for (let i = -5; i < 5; i++) { for (let j = -5; j < 5; j++) { for (let z = -5; z < 5; z++) { const cube = new THREE.Mesh(cubeGeometry, material); cube.position.set(i, j, z); scene.add(cube); } } }
|
线框效果
这样的效果不太好看,我们修改下材质,改成线框
1 2 3
| const material = new THREE.MeshBasicMaterial({ wireframe: true, });
|
鼠标交互效果
接下来,我想要给这个立方体添加一个效果,鼠标点击之后,让被点击的小立方体变成红色的
创建红色材质
1 2 3
| const redMaterial = new THREE.MeshBasicMaterial({ color: "#ff0000", });
|
监听鼠标的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const mouse = new THREE.Vector2();
window.addEventListener("click", (event) => { mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = -((event.clientY / window.innerHeight) * 2 - 1); });
|
通过 THREE.Raycaster 实现模型选中与信息显示
1 2 3 4
| const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
|
相交检测
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| let cubeArr = []; for (let i = -5; i < 5; i++) { for (let j = -5; j < 5; j++) { for (let z = -5; z < 5; z++) { const cube = new THREE.Mesh(cubeGeometry, material); cube.position.set(i, j, z); scene.add(cube); cubeArr.push(cube); } } }
let result = raycaster.intersectObjects(cubeArr);
result.forEach((item) => { item.object.material = redMaterial; });
|