我一直在尝试编写一个视图矩阵/查看矩阵,但我的代码中某处出现了错误,我需要帮助找到它。当我使用我的功能时,我得到一个空白屏幕,而不是我应该得到的三角形的测试视图。
public static Mat4 lookAt(
float eyeX, float eyeY, float eyeZ, //Where we are looking from
float centreX, float centreY, float centreZ, //Where we are looking to
float upX, float upY, float upZ) //Which way is up
{
Vec3 eye = new Vec3(eyeX, eyeY, eyeZ);
Vec3 target = new Vec3(centreX, centreY, centreZ);
Vec3 up = new Vec3(upX, upY, upZ);
Vec3 zaxis = normal(subtract(target,eye)); // The "forward" vector.
Vec3 xaxis = normal(cross(up, zaxis)); // The "right" vector.
Vec3 yaxis = cross(zaxis, xaxis); // The "up" vector.
// [ right.x right.y right.z 0]
// [ up.x up.y up.z 0]
// [-forward.x -forward.y -forward.z 0]
// [ 0 0 0 1]
Mat4 orientation = new Mat4(
new Vec4( xaxis.get()[0], yaxis.get()[0], -zaxis.get()[0], +0.0f ), //Column 1
new Vec4( xaxis.get()[1], yaxis.get()[1], -zaxis.get()[1], +0.0f ), //Column 2
new Vec4( xaxis.get()[2], yaxis.get()[2], -zaxis.get()[2], +0.0f ), //Column 3
new Vec4( +0.0f, +0.0f, +0.0f, +1.0f) //Column 4
);
Mat4 translation = new Mat4 (
new Vec4( +1.0f, +0.0f, +0.0f, +0.0f ), //Column 1
new Vec4( +0.0f, +1.0f, +0.0f, +0.0f ), //Column 2
new Vec4( +0.0f, +0.0f, +1.0f, +0.0f ), //Column 3
new Vec4( -eye.get()[0], -eye.get()[1], -eye.get()[2], +1.0f) //Column 4
);
return multiply(orientation, translation);
}
这适用于右手坐标系。所有矩阵都是列专业;它们从a11开始构建,从第一列向下移动到a41,然后到a12,依此类推到a44。
我已经完成了以下功能,我很确定它们是正确的,但我已将它们包括在内,以防我忽略了一些内容:
Vec3 normal(Vec3 a)
{
Vec3 unit;
float[] v_a = a.get();
float v_mag = magnitude(a);
unit = new Vec3(v_a[0]/v_mag, v_a[1]/v_mag, v_a[2]/v_mag);
return unit;
}
-
float magnitude(Vec3 a)
{
float[] v_a = a.get();
return( (float)Math.sqrt(
Math.pow( (double)v_a[0], 2) +
Math.pow( (double)v_a[1], 2) +
Math.pow( (double)v_a[2], 2)
) // -- end sqrt --
); // -- return --
}
-
Vec3 cross(Vec3 a, Vec3 b)
{
Vec3 crossProduct;
float[] v_a = a.get();
float[] v_b = b.get();
crossProduct = new Vec3(
v_a[1]*v_b[2] - v_a[2]*v_b[1], //cx = ay*bz - az*by
v_a[2]*v_b[0] - v_a[0]*v_b[2], //cy = az*bx - ax*bz
v_a[0]*v_b[1] - v_a[1]*v_b[0] //cz = ax*by - ay*bz
);
return(crossProduct);
}
所有矢量分配都是正确的。 get()返回一个float []。
答案 0 :(得分:0)
看起来您使用的算法类似于此页面中描述的算法: http://www.cs.virginia.edu/~gfx/Courses/1999/intro.fall99.html/lookat.html
看来你在取向矩阵中否定了错误的东西。当你应该在方向矩阵中否定整个zaxis向量时,你否定每个轴向量的z分量。