【问题标题】:translating buffer after rotating旋转后平移缓冲区
【发布时间】:2017-09-20 15:53:44
【问题描述】:

我希望能够从中心旋转一个四边形。为此,我遵循以下步骤:

  1. 转换为 (0, 0)
  2. 旋转
  3. 回到目的地

我被困在第三点。当我旋转矩阵时,我想将它相对于屏幕向右移动一点,但它会相对于旋转向右移动一点。

这是我的代码:

var moveBackX = ((-usedSprite.originX)/usedViewWidth);
var moveBackY = (((usedSprite.originY)))/usedViewHeight;
//The translation is already at (0, 0, 0)
mat4.rotateZ(mvMatrix, mvMatrix, rotation);
mat4.translate(mvMatrix, mvMatrix, [(moveBackX)/scaleX, moveBackY/scaleY, 0.0]);

mat4.translate(mvMatrix, mvMatrix, [((xPos)/scaleX), (-(yPos)/scaleY), 0.0]);

我该如何解决这个问题?

【问题讨论】:

    标签: javascript matrix webgl image-rotation


    【解决方案1】:

    您只需将转换的顺序更改为:

    mat4.rotateZ(mvMatrix, mvMatrix, rotation);
    mat4.translate(mvMatrix, mvMatrix, [(moveBackX)/scaleX, moveBackY/scaleY, 0.0]);
    
    mat4.translate(mvMatrix, mvMatrix, [((xPos)/scaleX), (-(yPos)/scaleY), 0.0]);
    

    这是一个使用 Context2D 的小演示:

    const ctx = maincanvas.getContext('2d');
    
    maincanvas.width = 320;
    maincanvas.height = 240;
    
    function drawRect(color) {
      ctx.strokeStyle = color;
      ctx.beginPath();
      ctx.rect(0, 0, 50, 50);
      ctx.stroke();
    }
    
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.translate(100, 0);
    drawRect('#ff8888');
    ctx.rotate(Math.PI/12);
    drawRect('#ff0000');
    
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.rotate(Math.PI/12);
    drawRect('#88ff88');
    ctx.translate(100, 0);
    drawRect('#00ff00');
    canvas {
      width: 320px;
      height: 240px;
      border: 1px solid black;
    }
    <canvas id='maincanvas'></canvas>

    【讨论】:

      【解决方案2】:

      您必须在我们所说的“世界空间”而不是“本地空间”中应用翻译。您的 mat4.translate() 函数似乎在本地空间中执行翻译。

      更清楚地说,您的平移函数发生了什么,是平移向量乘以变换矩阵的旋转/缩放部分,这会沿对象的局部轴(即局部空间)产生这种平移)。为防止这种情况,您只需将平移向量添加到转换矩阵的平移部分即可。

      让我们假设以下变换 4x4 矩阵:

      Xx Xy Xz 0 // <- X axis
      Yx Yy Yz 0 // <- Y axis
      Zx Zy Zz 0 // <- Z axis
      Tx Ty Tz 1 // <- Translation
      

      地点:

      mat4[ 0] = Xx; mat4[ 1] = Xy;  mat4[ 2] = Xz; mat4[ 3] = 0; 
      mat4[ 4] = Yx; mat4[ 5] = Yy;  mat4[ 6] = Yz; mat4[ 7] = 0; 
      mat4[ 8] = Zx; mat4[ 9] = Zy;  mat4[10] = Zz; mat4[11] = 0; 
      mat4[12] = Tx; mat4[13] = Ty;  mat4[14] = Tz; mat4[15] = 1;
      

      旋转/缩放部分(轴)是定义在 [0] 到 [10](不包括 [3]、[7] 和 [11])内的 3x3 矩阵。翻译部分是[12]、[13]和[14]。

      要在世界空间中向这个变换矩阵添加平移,您只需执行以下操作:

      mat4[12] += TranslationX;
      mat4[13] += TranslationY;
      mat4[14] += TranslationZ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2012-12-25
        • 2017-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        相关资源
        最近更新 更多