Game Development Reference
In-Depth Information
Whoa, that was less complicated than expected. This will rotate any vector counter-clockwise
around the origin, no matter what interpretation you have of the vector.
Together with vector addition, subtraction, and multiplication by a scalar, we can actually
implement all the OpenGL matrix operations yourself. This is one part of the solution for further
increasing the performance of your BobTest from Chapter 7. This will be discussed in an
upcoming section. For now, let us concentrate on what was discussed and transfer it to code.
Implementing a Vector Class
Now we can create an easy-to-use vector class for 2D vectors. We call it Vector2 . It should have
two members for holding the x and y components of the vector. Additionally, it should have a
couple of nice methods that allow you to do the following:
ï?®
Add and subtract vectors
ï?®
Multiply the vector components with a scalar
ï?®
Measure the length of a vector
ï?®
Normalize a vector
ï?®
Calculate the angle between a vector and the x axis
ï?®
Rotate the vector
Java lacks operator overloading, so we have to come up with a mechanism that makes working
with the Vector2 class less cumbersome. Ideally, we should have something like the following:
Vector2 v = new Vector2();
v.add(10,5).mul(10).rotate(54);
We can easily achieve this by letting each of the Vector2 methods return a reference to the
vector itself. Of course, we also want to overload methods like Vector2.add() so that we can
pass in either two floats or an instance of another Vector2 . Listing 8-1 shows your Vector2 class
in its full glory, with comments added where appropriate.
Listing 8-1. Vector2.java; Implementing Some Nice 2D Vector Functionality
package com.badlogic.androidgames.framework.math;
import android.util.FloatMath;
public class Vector2 {
public static float TO_RADIANS = (1 / 180.0f) * ( float ) Math. PI ;
public static float TO_DEGREES = (1 / ( float ) Math. PI ) * 180;
public float x, y;
public Vector2() {
}
 
Search WWH ::




Custom Search