Game Development Reference
In-Depth Information
if
(len != 0) {
this
.x /= len;
this
.y /= len;
this
.z /= len;
}
return this
;
}
The
len()
and
nor()
methods are also essentially the same as in the
Vector2
class. All we do is
incorporate the new z coordinate into the calculations.
public
Vector3 rotate(
float
angle,
float
axisX,
float
axisY,
float
axisZ) {
inVec
[0] = x;
inVec
[1] = y;
inVec
[2] = z;
inVec
[3] = 1;
Matrix.
setIdentityM
(
matrix
, 0);
Matrix.
rotateM
(
matrix
, 0, angle, axisX, axisY, axisZ);
Matrix.
multiplyMV
(
outVec
, 0,
matrix
, 0,
inVec
, 0);
x =
outVec
[0];
y =
outVec
[1];
z =
outVec
[2];
return this
;
}
And here's our new
rotate()
method. As indicated earlier, it makes use of Android's
Matrix
class. The
Matrix
class essentially consists of a couple of static methods, like
Matrix.setIdentityM()
and
Matrix.rotateM()
. These operate on float arrays, similar to the ones
we defined earlier. A matrix is stored as 16 float values, and a vector is expected to have four
elements. We won't go into detail about the inner workings of the class; all we need is a way
to emulate the matrix capabilities of OpenGL ES on the Java side, and that's exactly what this
class offers to us. All of the methods work on a matrix and operate in exactly the same way as
glRotatef()
,
glTranslatef()
, and
glIdentityf()
in OpenGL ES.
The
rotate()
method starts off by setting the vector's components to the
inVec
array we defined
earlier. Next, we call
Matrix.setIdentityM()
on the
matrix
member of our class. This will
“clear� the matrix. With OpenGL ES, we used
glIdentityf()
to do the same thing with matrices
residing on the GPU. Next, we call
Matrix.rotateM()
. It takes the float array holding the matrix,
an offset into that array, the angle we want to rotate by in degrees, and the (unit length) axis we
want to rotate around. This method is equivalent to
glRotatef()
. It will multiply the given matrix
by a rotation matrix. Finally, we call
Matrix.multiplyMV()
, which will multiply our vector stored in
inVec
by the matrix. This applies all of the transformations stored in the matrix to the vector. The
result will be output in
outVec
. The rest of the method just grabs the resulting new components
from the
outVec
array and stores them in the
Vector3
class's members.
Note
You can use the
Matrix
class to do a lot more than just rotate vectors. It operates in
exactly the same way as OpenGL ES in its effects on the passed-in matrix.