首页 > 解决方案 > 围绕局部轴的对象旋转

问题描述

我想围绕他的坐标旋转一个物体。例如,我想在屏幕上连续显示三个立方体,假设我有一个具有属性 transformMatrix 的类形状。

export class Shape {
  constructor(vertices, indices, gl) {
  this.id = ++id
  this.gl = gl;
  this.vertices = vertices;
  this.indices = indices;
  this.color = [];
  this.generateColor();

  this.transformMatrix = mat4.create();
...
  this.baseTranslation = {}
...
}

默认情况下,形状按顶点绘制。这是一个立方体顶点。

-0.5, -0.5,  0.5,
 0.5, -0.5,  0.5,
 0.5,  0.5,  0.5,
-0.5,  0.5,  0.5,
 0.5, -0.5, -0.5,
-0.5, -0.5, -0.5,
-0.5,  0.5, -0.5,
 0.5,  0.5, -0.5,

和指数

   0, 1, 2,
   0, 2, 3,
   4, 5, 6,
   4, 6, 7,
   5, 0, 3,
   5, 3, 6,
   1, 4, 7,
   1, 7, 2,
   5, 4, 1,
   5, 1, 0,
   3, 2, 7,
   3, 7, 6,

然后对于初始化期间的每个形状,我将对其进行一点翻译并缩放以在屏幕上连续看到它们。

// translation values for each shape
const baseTranslation = [
    [-1.5, 0, 0],
    [0, 0, 0],
    [1.5, 0, 0],
]
// usage
// shapes.forEach((shape,i) => 
//   shape.setBaseTranslation(baseTranslation[i]))

setBaseTranslation(coordinates) {
  const BASE_SCALE = 0.33
  this.baseTranslation.x = coordinates[0]
  this.baseTranslation.y = coordinates[1]
  this.baseTranslation.z = coordinates[2]

  const {x,y,z} = this.baseTranslation
  const array = [x,y,z]

  mat4.scale(this.transformMatrix, this.transformMatrix, [BASE_SCALE, 
    BASE_SCALE, BASE_SCALE])
  mat4.translate(this.transformMatrix, this.transformMatrix, array)
}

这就是我在屏幕上看到的。 屏幕

我可以选择哪个形状处于活动状态并对其进行变换。在 keydown 事件中,我开始转换活动形状。如果我想围绕形状轴进行转换(旋转),我需要将其转换为(0,0)全局坐标,然后旋转,然后再转换回来。我想将一个矩阵用于所有转换。这就是我的转换函数在 keydown 事件上的样子。

// {Array} @actions
//   @name mat4 function
//   {GLFloat32Array|GLFloat} @value to transform

transform(actions) {
  const {x, y, z} = this.baseTranslation

  // translate back 
  mat4.translate(this.transformMatrix, this.transformMatrix, [x, y, z]);

  actions.forEach(action => {
    const key = action.name;
    const value = action.value;

    mat4[key](this.transformMatrix, this.transformMatrix, value);
  });

  // translate to center
  mat4.translate(
     this.transformMatrix, 
     this.transformMatrix, 
     [-(x), -(y), -(z)]);

}

当我旋转中间框时,旋转按预期工作。

在此处输入图像描述

但是当我切换到第一个或最后一个时,旋转会围绕另一个点。

在此处输入图像描述

我究竟做错了什么?

标签: 3dwebglwebgl2

解决方案


推荐阅读