场景
作为刚刚接触 Three.js 的小白,在工作中遇到下面的需求:
- 加载一个 3D 模型
- 通过代码切换预设的任意模型的视角
最终效果(在线示例):
👆基于官方示例增加的控制代码
我们通过官方示例可以知道,只要使用 OrbitControls 就可以通过鼠标调整模型的视角。可是,能不能通过代码,切换特定的视角呢?有没有官方的 API 可以实现这个交互呢?小白暂时未能找到拿来即用的示例代码。
基本原理
通过 AI 可以得知相关矩阵变化的公式原理:
通过 AI,我们还能得到上面原理的核心算法代码:
// Function to multiply matrix and point
function multiplyMatrixAndPoint(matrix, point) {
let result = []
for (let i = 0; i < matrix.length; i++) {
result[i] =
matrix[i][0] * point[0] +
matrix[i][1] * point[1] +
matrix[i][2] * point[2]
}
return result
}
function rotatePoint(x, y, z, rotateZ, rotateY) {
// Convert degrees to radians
const radZ = (rotateZ * Math.PI) / 180
const radY = (rotateY * Math.PI) / 180
// Rotation matrix around Z-axis
const Rz = [
[Math.cos(radZ), -Math.sin(radZ), 0],
[Math.sin(radZ), Math.cos(radZ), 0],
[0, 0, 1],
]
// Rotation matrix around Y-axis
const Ry = [
[Math.cos(radY), 0, Math.sin(radY)],
[0, 1, 0],
[-Math.sin(radY), 0, Math.cos(radY)],
]
// Apply rotation matrices
let pointAfterZ = this.multiplyMatrixAndPoint(Rz, [x, y, z])
let finalPoint = this.multiplyMatrixAndPoint(Ry, pointAfterZ)
return finalPoint
}
输入:起始点 x, y, z;绕着 Z 轴旋转的角度;绕着 Y 轴旋转的角度;
输出:旋转后的新坐标 [x,y,z];
动画
基于上面坐标的计算,还要实现新旧坐标变化的过渡动画,这里可以用浏览器 API 的 requestAnimationFrame 实现:
/**
* 淡入淡出
* https://www.cnblogs.com/cloudgamer/archive/2009/01/06/Tween.html
* @param t 当前时间
* @param b 初始值
* @param c 增/减量
* @param d 持续时间
*/
cubicEaseInOut(t, b, c, d) {
if ((t /= d / 2)