使用Three.js如何通过代码动态改变模型的视角

场景

作为刚刚接触 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) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值