Reputation: 490
say for example I have a class named Matrix4x4 and the class has the following function:
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;
}
And in another class I have an object name modelMatrix that is an instance of Matrix4x4 which is initialized this way:
public Matrix4x4 modelMatrix = Matrix4x4.IdentityM();
Where the IdentityM() function contains:
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}
});
}
Now I have a little problem that I can't figure out. let's say for example that I have a rectangle with x, y, width and height. and now for example I do:
modelMatrix.translate(0.002f, 0.002f, 0);
Where the function translate contains:
public void translate(float x, float y, float z){
matrix[0][3] += x;
matrix[1][3] += y;
matrix[2][3] += z;
}
Using OpenGL ES when I send the modelMatrix to the shader, the object moves correctly, but when I calculate the vertices with modelMatrix, they stay the same and don't change, the function that calculates the vertices is:
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]
};
}
And the results in the log stay the same even though I move the object and the object moves in OpenGL, is this a problem with the calculation I'm doing? How can I correct it?
Upvotes: 2
Views: 2090
Reputation: 54592
In your MultiplyVec()
method, you're rounding all the intermediate values to integers:
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;
}
Since value
is a variable of type int
, all the partial sums will be rounded to integers. You need to use a float
variable for the intermediate value:
for(int i = 0; i < 4; i++){
float value = 0f;
...
Upvotes: 3