// tjh2dVector.java /** A simple class that manages a 2D location/vector in space given floats x and y. */ public class tjh2dVector extends Object { //-------------------------------------------------------------------------------- // data //-------------------------------------------------------------------------------- /** the coordinates of the location/vector */ public float x,y; //-------------------------------------------------------------------------------- // methods //-------------------------------------------------------------------------------- /** default constructor */ public tjh2dVector() { } /** initializing constructor */ public tjh2dVector(float a,float b) { x=a; y=b; } /** returns the dot product of the two vectors */ public static float DotProduct(tjh2dVector a,tjh2dVector b) { return a.x*b.x+a.y*b.y; } /** rotates this point by deg degrees around the point c */ public void RotateAround(tjh2dVector c,float deg) { // find sine and cosine of the angle float radians = deg*3.1415926535F/180.0F; float sine = (float)Math.sin(radians); float cosine = (float)Math.cos(radians); // rotate around the point tjh2dVector new_pos = new tjh2dVector(x-c.x,y-c.y); float temp = cosine*new_pos.x - sine*new_pos.y; new_pos.y = sine*new_pos.x + cosine*new_pos.y; new_pos.x = temp; x = c.x + new_pos.x; y = c.y + new_pos.y; } /** replaces this vector with its left-hand perpendicular */ public tjh2dVector Perp() { tjh2dVector v = new tjh2dVector(); v.x=-y; v.y=x; return v; } /** changes the length of the vector to one */ public tjh2dVector Normalize() { float l = Length(); tjh2dVector v = new tjh2dVector(); v.x=x/l; v.y=y/l; return v; } /** returns the length of the vector */ public float Length() { return (float)Math.sqrt(x*x+y*y); } /** return the unit vector with the correct angle anti-clockwise from the +ve x-axis */ public static tjh2dVector Cartesian(float degrees) { tjh2dVector v = new tjh2dVector(); v.x=(float)Math.cos(degrees*3.1415926535F/180.0F); v.y=(float)Math.sin(degrees*3.1415926535F/180.0F); return v; } /** returns the angle of the vector anticlockwise from the +ve x-axis */ public float Angle() { return (float)Math.atan2(x,y); } /** adds the two vectors together, returns the result */ public static tjh2dVector sum(tjh2dVector a,tjh2dVector b) { tjh2dVector v = new tjh2dVector(); v.x=a.x+b.x; v.y=a.y+b.y; return v; } /** subtracts b from a, returns the result */ public static tjh2dVector minus(tjh2dVector a,tjh2dVector b) { tjh2dVector v = new tjh2dVector(); v.x=a.x-b.x; v.y=a.y-b.y; return v; } /** multiplies the vector a by the scalar f, returns the result */ public static tjh2dVector mult(tjh2dVector a,float f) { tjh2dVector v = new tjh2dVector(); v.x=a.x*f; v.y=a.y*f; return v; } }