Reputation: 821
I have this 3x3 matrix which I'm using to preform basic transformations like translation, scaling and rotation, but the rotation part isn't working as it should. For any angle larger then 30 degrees or so, it just looks.. wierd.
The method looks like this:
public void rotate(float angle) {
double rads = angle * (Math.PI/180);
float sin = (float) Math.sin(rads);
float cos = (float) Math.cos(rads);
matrix[0][0] = cos;
matrix[0][1] = -sin;
matrix[1][0] = sin;
matrix[1][1] = cos;
}
And the methods applying the transformation:
For X:
public float[] applyTransformX(float[] x, float[] y) {
float[] transformed = new float[x.length];
for(int i=0; i<x.length; i++) {
transformed[i] = (x[i] * matrix[0][0]) + (y[i] * matrix[0][1] + matrix[0][2]);
System.out.println((x[i] * matrix[0][0]) + (y[i] * matrix[0][1] + matrix[0][2]));
}
return transformed;
}
For Y:
public float[] applyTransformY(float[] x, float[] y) {
float[] transformed = new float[x.length];
for(int i=0; i<x.length; i++) {
transformed[i] = (x[i] * matrix[1][0]) + (y[i] * matrix[1][1] + matrix[1][2]);
}
return transformed;
}
Are there any fundamental things I'm missing here? I'm aware of the fact that I'm not doing the transformations around a fixed point. Is that perhaps why I'm experiencing this problem?
As I said, the translation and scaling is working as it should.
Upvotes: 0
Views: 977
Reputation: 79807
All that I can think of is that there might be a rounding error resulting from a discrepancy in the sizes of the three terms that you're adding to get each x[i]
, and to get each y[i]
. My instinct would be to add in the translation term last, so that a sizable translation doesn't cause loss of significance in the terms that result from rotation. This just requires you removing some of your parentheses, so that the standard left-to-right order of operations kicks in. In other words, in the method for calculating the X values, write:
transformed[i] = x[i] * matrix[0][0] + y[i] * matrix[0][1] + matrix[0][2];
without any of the parentheses. Similarly, when calculating the Y values, write
transformed[i] = x[i] * matrix[1][0] + y[i] * matrix[1][1] + matrix[1][2];
If that doesn't help, then please post some actual numbers, so that we can see which calculations might be causing loss of significance. The fact that this works OK for small angles suggests that you are seeing a rounding error, as opposed to an actual incorrect calculation method.
Upvotes: 1
Reputation: 20560
The problem is in the computation of transformed[i]
in both cases:
for X it should be:
transformed[i] = (x[i] * matrix[0][0]) + (y[i] * matrix[0][1]);
and for Y it should be:
transformed[i] = (x[i] * matrix[1][0]) + (y[i] * matrix[1][1]);
If you include matrix[0][2]
and matrix[1][2]
this would for a Z component, however those should evaluate to 0 for a rotation around the Z axis (matrix[2][2]
would be 1 although to be complete). You probably just forgot to reinitialize them…
Upvotes: 0