Search code examples
javascriptmatrixwebglimage-rotation

translating buffer after rotating


I want to be able to rotate a quad from the center. To do this I am following these steps:

  1. translate to (0, 0)
  2. rotate
  3. move back to destination point

I am stuck at point three. When I have rotated the matrix I want to move it one point to the right relative to the screen, but it moves one point to the right relative to the rotation instead.

enter image description here

Here is my code:

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]);

How do I fix this?


Solution

  • You just have to change the order of the transformations to:

    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]);
    

    Here is a little demonstration using 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>