【问题标题】:How to rotate around Z axis using transformation matrix in 3D?如何使用 3D 中的变换矩阵围绕 Z 轴旋转?
【发布时间】:2016-07-01 07:35:31
【问题描述】:

在 Lua 中,我设置了一个单位矩阵:

local ident_matrix = {
 {1,0,0,0},
 {0,1,0,0},
 {0,0,1,0},
 {0,0,0,1},
}

然后将其更新为包含 x=100、y=0、z=0 处的点:

ident_matrix = {
 {100,0,0,0},
 {0,0,0,0},
 {0,0,0,0},
 {0,0,0,1},
}

然后我将旋转值定义为 90 度的弧度:

local r = math.rad(90)

由此我创建了一个 Z 轴旋转矩阵:

local rotate_matrix = {
 {math.cos(r),math.sin(r),0,0},
 {-math.sin(r),math.cos(r),0,0},
 {0,0,1,0},
 {0,0,0,1},
}

然后从这里使用矩阵乘法将 Z 轴旋转矩阵应用于 {100,0,0} 点:

local function multiply( aMatrix, bMatrix )
    if #aMatrix[1] ~= #bMatrix then       -- inner matrix-dimensions must agree
        return nil      
    end 

    local empty = newEmptyMatrix()

    for aRow = 1, #aMatrix do
        for bCol = 1, #bMatrix[1] do
            local sum = empty[aRow][bCol]
            for bRow = 1, #bMatrix do
                sum = sum + aMatrix[aRow][bRow] * bMatrix[bRow][bCol]
            end
            empty[aRow][bCol] = sum
        end
    end

    return empty
end

local rotated = multiply( rotate_matrix, ident_matrix )

矩阵乘法取自 RosettaCode.org: https://rosettacode.org/wiki/Matrix_multiplication#Lua

我期待rotated 矩阵输出与以下内容相同:

local expected = {
 { 0, 0, 0, 0 },
 { 0, 100, 0, 0 },
 { 0, 0, 0, 0 },
 { 0, 0, 0, 0 },
}

或者,如果使用左手 (?) 计算,Y 值可能是 -100。 我最终得到的是:

{
 { 0, 100, 0, 0 },
 { 0, 0, 0, 0 },
 { 0, 0, 0, 0 },
 { 0, 0, 0, 1 },
}

谁能告诉我我做错了什么并纠正我的代码?

【问题讨论】:

  • 为什么使用 4x4-matrix 来存储 3D 空间中的点(而不是 1x3 向量)?
  • 老实说,我不确定。我认为最简单的成功途径是确保我所有的矩阵都具有相同的维度——尽管我知道 A 的行必须等于 B 的列。
  • 谢谢!我已将身份矩阵更改为一行四个单元格,一切正常。 #史诗。

标签: lua 3d matrix-multiplication transformation-matrix


【解决方案1】:

正如@egor-skriptunoff 的评论所暗示的那样......

在 Lua 中,我设置了一个单位矩阵:

local ident_matrix = {
 {1,1,1,1},
}

然后将其更新为包含 x=100、y=0、z=0 处的点:

ident_matrix = {
 {100,0,0,1},
}

然后我将旋转值定义为 90 度的弧度:

local r = math.rad(90)

由此我创建了一个 Z 轴旋转矩阵:

local rotate_matrix = {
 {math.cos(r),math.sin(r),0,0},
 {-math.sin(r),math.cos(r),0,0},
 {0,0,1,0},
 {0,0,0,1},
}

然后从这里使用矩阵乘法将 Z 轴旋转矩阵应用于 {100,0,0} 点:

local function multiply( aMatrix, bMatrix )
    if #aMatrix[1] ~= #bMatrix then       -- inner matrix-dimensions must agree
        return nil      
    end 

    local empty = newEmptyMatrix()

    for aRow = 1, #aMatrix do
        for bCol = 1, #bMatrix[1] do
            local sum = empty[aRow][bCol]
            for bRow = 1, #bMatrix do
                sum = sum + aMatrix[aRow][bRow] * bMatrix[bRow][bCol]
            end
            empty[aRow][bCol] = sum
        end
    end

    return empty
end

local rotated = multiply( rotate_matrix, ident_matrix )

矩阵乘法取自 RosettaCode.org: https://rosettacode.org/wiki/Matrix_multiplication#Lua

现在,我得到了我的预期:

local expected = {
 { 0, 100, 0, 0 },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多