反向执行矩阵乘法

时间:2022-11-07 13:49:54

Follow-up for: Calculating world coordinates from camera coordinates

跟进:从摄像机坐标计算世界坐标

I'm multiplying a 2D vector with a transformation matrix (OpenGL's model-view matrix) to get world coordinates from my camera coordinates.

我将2D矢量与变换矩阵(OpenGL的模型 - 视图矩阵)相乘,以从我的相机坐标获取世界坐标。

I do this calculation like this:

我做这样的计算:

private Vector2f toWorldCoordinates(Vector2f position) {

    glPushMatrix();
    glScalef(this.zoom, this.zoom, 1);
    glTranslatef(this.position.x, this.position.y, 0);
    glRotatef(ROTATION, 0, 0, 1);

    ByteBuffer m = ByteBuffer.allocateDirect(64);
    m.order(ByteOrder.nativeOrder());
    glGetFloatv(GL_MODELVIEW_MATRIX, m);

    float x = (position.x * m.getFloat(0)) + (position.y * m.getFloat(4)) + m.getFloat(12);
    float y = (position.x * m.getFloat(16)) + (position.y * m.getFloat(20)) + m.getFloat(28);

    glPopMatrix();
    return new Vector2f(x, y);
}

Now I also want to do this vice-versa: calculate the camera coordinates for a position in the world. How can I reverse this calculation?

现在我也想反过来这样做:计算世界上某个位置的摄像机坐标。我该如何改变这个计算?

1 个解决方案

#1


To create a matrix representing the inverse transform to the one above, apply the transforms in reverse, with negative quantities for the rotation and translation and an inverse quantity for the zoom:

要创建表示上述逆变换的矩阵,请反向应用变换,使用负数量进行旋转和平移,并使用反量变换:

glRotatef(-ROTATION, 0, 0, 1);
glTranslatef(-this.position.x, -this.position.y, 0);
glScalef(1.0f / this.zoom, 1.0f / this.zoom, 1);

Then multiply by the position vector as before.

然后如前所述乘以位置矢量。

The alternative is to compute the inverse matrix, but this way is much simpler.

另一种方法是计算逆矩阵,但这种方法更简单。

#1


To create a matrix representing the inverse transform to the one above, apply the transforms in reverse, with negative quantities for the rotation and translation and an inverse quantity for the zoom:

要创建表示上述逆变换的矩阵,请反向应用变换,使用负数量进行旋转和平移,并使用反量变换:

glRotatef(-ROTATION, 0, 0, 1);
glTranslatef(-this.position.x, -this.position.y, 0);
glScalef(1.0f / this.zoom, 1.0f / this.zoom, 1);

Then multiply by the position vector as before.

然后如前所述乘以位置矢量。

The alternative is to compute the inverse matrix, but this way is much simpler.

另一种方法是计算逆矩阵,但这种方法更简单。