TajBot (Robocode bot)

Copyright Tristan Aubrey-Jones December 2005.

Vector.java

home Home   up Up   ( Download )


package tajy; public class Vector { double x, y; public Vector(double x, double y) { this.x = x; this.y = y; } public Vector(Vector v) { this.x = v.x; this.y = v.y; } private static double getGoodDegrees(double angle) { return angle % 360; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public double getBearingRadians() { double angle = Math.atan(x / y); // -x if (x < 0) { // -y if (y < 0) { return angle + Math.PI; } // +y else { return angle + 2 * Math.PI; } } // +x else { // -y if (y < 0) { return angle + Math.PI; } // +y else { return angle; } } } public double getBearingDegrees() { double angle = Math.toDegrees(getBearingRadians()); if (angle < 0) return angle + 360; else return angle; } public double getDistance() { // make sure are positive double x = this.x; if (x < 0) x = -x; double y = this.y; if (y < 0) y = -y; // return magnitude |r| of vector return Math.sqrt((x*x) + (y*y)); } public Vector add(Vector v) { return new Vector(x + v.x, y + v.y); } /** * @param angle - Angle in radians from the +ve y axis * @param distance - distance along line to travel * @return A vector representing that movement */ public static Vector fromAngleRadians(double angle, double distance) { Vector r = new Vector(0, 0); r.x = distance * Math.sin(angle); r.y = distance * Math.cos(angle); return r; } /** * @param angle - Angle in degrees from the +ve y axis * @param distance - distance along line to travel * @return A vector representing that movement */ public static Vector fromAngleDegrees(double angle, double distance) { angle = Vector.getGoodDegrees(angle); return fromAngleRadians(Math.toRadians(angle), distance); } public Vector subtract(Vector v) { return new Vector(x - v.x, y - v.y); } public double dotProduct(Vector v) { return (x * v.x) + (y * v.y); } public String toString() { return '(' + Double.toString(x) + ", " + Double.toString(y) + ')'; } public double distanceTo(Vector v) { Vector r = v.subtract(this); return r.getDistance(); } }