Game Development Reference
In-Depth Information
Otherwise, we divide each component of the vector by its length to arrive at a unit-length vector.
For chaining, we return the reference to this vector again.
public float angle() {
float angle = ( float ) Math. atan2 (y, x) * TO_DEGREES ;
if (angle < 0)
angle += 360;
return angle;
}
The angle() method calculates the angle between the vector and the x axis using the atan2()
method, as discussed previously. We have to use the Math.atan2() method, as the FloatMath
class doesn't have this method. The returned angle is given in radians, so we convert it to
degrees by multiplying it by TO_DEGREES . If the angle is less than zero, we add 360˚ to it so that
we can return a value in the range 0 to 360˚.
public Vector2 rotate( float angle) {
float rad = angle * TO_RADIANS ;
float cos = FloatMath. cos (rad);
float sin = FloatMath. sin (rad);
float newX = this .x * cos - this .y * sin;
float newY = this .x * sin + this .y * cos;
this .x = newX;
this .y = newY;
return this ;
}
The rotate() method simply rotates the vector around the origin by the given angle. Since the
FloatMath.cos() and FloatMath.sin() methods expect the angle to be given in radians, we
first convert them from degrees to radians. Next, we use the previously defined equations to
calculate the new x and y components of the vector, and then return the vector itself, again for
chaining.
public float dist(Vector2 other) {
float distX = this .x - other.x;
float distY = this .y - other.y;
return FloatMath. sqrt (distX * distX + distY * distY);
}
public float dist( float x, float y) {
float distX = this .x - x;
float distY = this .y - y;
return FloatMath. sqrt (distX * distX + distY * distY);
}
}
Finally, we have two methods that calculate the distance between this vector and another vector.
 
Search WWH ::




Custom Search