【问题标题】:How to rotate 3d point?如何旋转 3d 点?
【发布时间】:2019-11-19 21:18:06
【问题描述】:

我目前正在用 js 开发一个 3d 渲染器。

我想渲染立方体 - 效果很好 - 但我想做的是旋转每个立方体。

所以我得到了一个立方体的一些顶点,我想围绕它自己旋转每个立方体的 x/y/z(俯仰、滚动、偏航)。

这是3d旋转功能:

let rotate3d = (points = [0,0,0], pitch = 0, roll = 0, yaw = 0) => {
    let cosa = Math.cos(yaw),
        sina = Math.sin(yaw);
    let cosb = Math.cos(pitch),
        sinb = Math.sin(pitch);
    let cosc = Math.cos(roll),
        sinc = Math.sin(roll);
    let Axx = cosa*cosb,
        Axy = cosa*sinb*sinc - sina*cosc,
        Axz = cosa*sinb*cosc + sina*sinc;
    let Ayx = sina*cosb,
        Ayy = sina*sinb*sinc + cosa*cosc,
        Ayz = sina*sinb*cosc - cosa*sinc;
    let Azx = -sinb,
        Azy = cosb*sinc,
        Azz = cosb*cosc;
    let px = points[0];
    let py = points[1];
    let pz = points[2];
    points[0] = Axx*px + Axy*py + Axz*pz;
    points[1] = Ayx*px + Ayy*py + Ayz*pz;
    points[2] = Azx*px + Azy*py + Azz*pz;
    return points;
  }

这是我的渲染器例程中的一个 sn-p:

for (let vert of cube.vertex) {
  let x = vert[0] - camera.position[0],
      y = vert[1] - camera.position[1],
      z = vert[2] - camera.position[2];

  if (cube.rotation) {
    cube.rotation += Math.PI * 0.02;
    let p = rotate(vert.slice(0), cube.r, 0, 0)
    x = p[0] - camera.position[0]
    y = p[1] - camera.position[1]
    z = p[2] - camera.position[2]
  }
  
  # ... draw polygons (cube) by converting 3d coordinates to 2d coordinates.
}

See gif 1

所以:如果立方体在 [0, -1, 0] 处生成,程序将围绕 y 轴(顺时针)旋转这个立方体。但是将 spawn 更改为 [1, -1, 0] 可以让立方体围绕同一点(原点)旋转,但空间为 1。我想在它的 spawn 上旋转立方体!

See gif 2

编辑:这是生成立方体例程:

spawn(p) {
    this.position = p;
    const vertex = [[-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [-1,-1,1], [1,-1,1], [1,1,1], [-1,1,1]];
    this.vertex = []
    for (let vert of vertex) {
      let position = []
      for (let i=0; i<vert.length; i++) position.push(vert[i]/2 + this.position[i])
      this.vertex.push(position)
    }
}

所以我的问题是:如何编辑旋转功能以添加我想要旋转立方体的原点?

【问题讨论】:

    标签: javascript arrays 3d render vertex


    【解决方案1】:

    指定旋转点的最简单方法是:

    1. 平移(移动)对象,使旋转点位于原点 (0,0,0)
    2. 旋转所需数量
    3. 与第 1 步中的翻译相反。

    在(伪)代码中:

    var translationVector = originPoint.minus(rotationPoint);
    myObject.translate(translationVector);
    myObject.rotate(eulerX, eulerY, eulerZ);
    myObject.translate(-translationVector);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2014-12-26
      • 1970-01-01
      • 2019-01-27
      • 2017-08-28
      • 1970-01-01
      相关资源
      最近更新 更多