You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的2D旋转矩阵存在什么问题?Z轴旋转4x4矩阵代码求助

围绕Z轴旋转的4x4矩阵函数的问题分析

先看你给出的代码片段:

function rotation4x4(angle: number, output: number[], origin_x: number = 0.0, origin_y: number = 0.0) { 
  let x = origin_x; 
  let y = origin_y; 
  let r00 = cos(angle); 
  let r01 = -sin(angle); 
  let r10 = sin(angle); 
  let r11 = cos(angle); 
  mat4x4_set(output, 0, 0, r00); 
  mat4x4_set(output, 0, 1, r01); 
  mat4x4_set(output, 0, 2, x-r00*x-r01*y); 
  mat4x4_set(output, 0, 3, y-r10*x-r11*y); 
  mat4x4_set(output, 1, 0, r10); 
  mat4x4_set(output, 1, 1, r11); 
  mat4x4_set(output, ...
}

从代码来看,这个旋转矩阵函数存在几个关键问题:

  • 平移分量的位置完全错误
    4x4变换矩阵中,平移分量应该放在每行的第4列(索引为3的位置),而Z轴旋转不会影响Z轴相关的元素,所以行0、行1的第3列((0,3)和(1,3))才是X、Y方向的平移值。但你现在把X平移值放到了(0,2),Y平移值放到了(0,3),这会导致旋转后的坐标完全错乱——不仅平移方向不对,还会错误修改Z坐标的计算(因为(0,2)是Z轴的旋转分量位,Z轴旋转时这里应该是0)。

  • 未正确填充Z轴和齐次坐标行
    围绕Z轴旋转的4x4矩阵,第三行(索引2)应该是[0, 0, 1, 0](保证Z坐标不受旋转影响),第四行(索引3)必须是[0, 0, 0, 1](维持齐次坐标的正确性)。你的代码完全没处理这两行,如果output数组没有预先初始化全为0或正确值,这两行的垃圾数据会彻底破坏变换结果,比如导致Z坐标被错误修改,或者齐次坐标计算失效。

  • Y平移分量的行位置错误
    你计算的Y方向平移值y - r10*x - r11*y是正确的,但它应该被放到(1,3)的位置(行1,列3),而不是(0,3)。现在这个值被错误地放到了行0的列3,会导致X方向的平移被Y值覆盖,Y方向的平移完全缺失。

最后,给你一个修正后的核心逻辑参考:

// 正确设置Z轴旋转的核心元素
mat4x4_set(output, 0, 0, r00); 
mat4x4_set(output, 0, 1, r01); 
mat4x4_set(output, 0, 2, 0); // Z轴旋转不影响X-Z/Y-Z分量
mat4x4_set(output, 0, 3, x - r00*x - r01*y); // 正确的X平移位置

mat4x4_set(output, 1, 0, r10); 
mat4x4_set(output, 1, 1, r11); 
mat4x4_set(output, 1, 2, 0); 
mat4x4_set(output, 1, 3, y - r10*x - r11*y); // 正确的Y平移位置

// 填充Z轴和齐次行
mat4x4_set(output, 2, 0, 0);
mat4x4_set(output, 2, 1, 0);
mat4x4_set(output, 2, 2, 1);
mat4x4_set(output, 2, 3, 0);

mat4x4_set(output, 3, 0, 0);
mat4x4_set(output, 3, 1, 0);
mat4x4_set(output, 3, 2, 0);
mat4x4_set(output, 3, 3, 1);

内容的提问来源于stack exchange,提问作者edvinHolm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:09:11