Game Development Reference
In-Depth Information
public Vector2 add(Vector2 other) {
this .x += other.x;
this .y += other.y;
return this ;
}
public Vector2 sub( float x, float y) {
this .x -= x;
this .y -= y;
return this ;
}
public Vector2 sub(Vector2 other) {
this .x -= other.x;
this .y -= other.y;
return this ;
}
The add() and sub() methods come in two flavors: in one case, they work with two float
arguments, while in the other case, they take another Vector2 instance. All four methods return a
reference to this vector so that we can chain operations.
public Vector2 mul( float scalar) {
this .x *= scalar;
this .y *= scalar;
return this ;
}
The mul() method simply multiplies the x and y components of the vector with the given scalar
value, and it returns a reference to the vector itself, for chaining.
public float len() {
return FloatMath. sqrt (x * x + y * y);
}
The len() method calculates the length of the vector exactly, as defined previously. Note that we
use the FloatMath class instead of the usual Math class that Java SE provides. This is a special
Android API class that works with floats instead of doubles, and it is a little bit faster than the
Math equivalent, at least on older Android versions.
public Vector2 nor() {
float len = len();
if (len != 0) {
this .x /= len;
this .y /= len;
}
return this ;
}
The nor() method normalizes the vector to unit length. We use the len() method internally
to first calculate the length. If it is zero, we can bail out early and avoid a division by zero.
 
Search WWH ::




Custom Search