Java 矩阵向量乘法
例如,假设我有一个名为Matrix4x4的类,该类具有以下函数:Java 矩阵向量乘法,java,opengl,math,opengl-es,Java,Opengl,Math,Opengl Es,例如,假设我有一个名为Matrix4x4的类,该类具有以下函数: public float[] MultiplyVec(float[] vec){ float[] newV = new float[4]; for(int i = 0; i < 4; i++){ int value = 0; for(int j = 0; j < 4; j++){ value += matrix[i][j] * vec[j];
public float[] MultiplyVec(float[] vec){
float[] newV = new float[4];
for(int i = 0; i < 4; i++){
int value = 0;
for(int j = 0; j < 4; j++){
value += matrix[i][j] * vec[j];
}
newV[i] = value;
}
return newV;
}
其中IdentityM()函数包含:
public static Matrix4x4 IdentityM(){
return new Matrix4x4(new float[][]{
{1f, 0f, 0f, 0f},
{0f, 1f, 0f, 0f},
{0f, 0f, 1f, 0f},
{0f, 0f, 0f, 1f}
});
}
public void translate(float x, float y, float z){
matrix[0][3] += x;
matrix[1][3] += y;
matrix[2][3] += z;
}
现在我有一个小问题,我想不出来。
比如说,我有一个x,y,宽度和高度的矩形。
举个例子,我会:
modelMatrix.translate(0.002f, 0.002f, 0);
其中函数translate包含:
public static Matrix4x4 IdentityM(){
return new Matrix4x4(new float[][]{
{1f, 0f, 0f, 0f},
{0f, 1f, 0f, 0f},
{0f, 0f, 1f, 0f},
{0f, 0f, 0f, 1f}
});
}
public void translate(float x, float y, float z){
matrix[0][3] += x;
matrix[1][3] += y;
matrix[2][3] += z;
}
使用OpenGL ES当我将modelMatrix发送到着色器时,对象会正确移动,但当我使用modelMatrix计算顶点时,它们保持不变且不会更改,计算顶点的函数是:
public float[] getVertices(){
// Vertices in object space:
float[] vector1 = {x, y, 0f, 1f};
float[] vector2 = {x + width, y, 0f, 1f};
float[] vector3 = {x + width, y + height, 0f, 1f};
float[] vector4 = {x, y, 0f, 1f};
// Calculate the vertices in world space:
float[] vector1r = modelMatrix.MultiplyVec(vector1);
float[] vector2r = modelMatrix.MultiplyVec(vector2);
float[] vector3r = modelMatrix.MultiplyVec(vector3);
float[] vector4r = modelMatrix.MultiplyVec(vector4);
if(LoggerConfig.ON) Log.d("Middle Vertex", vector1r[2] + ", "
+ vector1r[3]);
return new float[] {
vector1r[0], vector1r[1],
vector2r[0], vector2r[1],
vector3r[0], vector3r[1],
vector4r[0], vector4r[1]
};
}
日志中的结果保持不变,即使我在OpenGL中移动了对象,对象也在移动,这是我正在进行的计算的问题吗?如何更正它?在MultiplyVec()
方法中,将所有中间值舍入为整数:
for(int i = 0; i < 4; i++){
int value = 0;
for(int j = 0; j < 4; j++){
value += matrix[i][j] * vec[j];
}
newV[i] = value;
}
嗯,是的,我忘了(那些小错误总是发生)。但问题是它仍然给我同样的结果。。。没帮上忙..嗨,不知道你能不能在这方面给我一些启发?我指的是它背后的推理和数学,以及如何获得它们?提前非常感谢。@Unheilig好吧,我在对象空间中取了顶点。然后在空间中移动顶点(称为世界空间)后,为了得到顶点,我需要将模型矩阵与对象的每个顶点相乘,因为我只修改模型矩阵,然后为了得到顶点,我需要将对象空间顶点与模型矩阵相乘,只有这样,我才能在移动它们后得到顶点。就这样:)谢谢你的解释。