Advertisement
Guest User

2D Vector class

a guest
Dec 29th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. public class Vec {
  2.     public final static Vec X_AXIS=new Vec(1,0);
  3.     public final static Vec Y_AXIS=new Vec(0,1);
  4.     public final static Vec ORIGIN=new Vec(0,0);
  5.    
  6.     final double x,y;
  7.    
  8.     public Vec(double x, double y) {
  9.         this.x=x;
  10.         this.y=y;
  11.     }
  12.     public double dotProduct(Vec v) {
  13.         return x*v.x+y*v.y;
  14.     }
  15.     public double crossProduct(Vec v) {
  16.         double r=x*v.y-y*v.x;
  17.         return r;
  18.     }
  19.     public double angle() {
  20.         return Math.atan2(y,x);
  21.     }
  22.     public double angleTo(Vec v) {
  23.         double angle=v.angle()-angle();
  24.         while(angle <= -Math.PI) angle+=Math.PI*2;
  25.         while(angle > Math.PI) angle-=Math.PI*2;
  26.         return angle;
  27.     }
  28.     public double getLength() {
  29.         return Math.sqrt(x*x+y*y);
  30.     }
  31.     public Vec translate(Vec v) {
  32.         return new Vec(this.x-v.x, this.y-v.y);
  33.     }
  34.     public Vec rotate90() {
  35.         return new Vec(-y, x);
  36.     }
  37.     public Vec rotate270() {
  38.         return new Vec(y, -x);
  39.     }
  40.     public Vec rotate180() {
  41.         return new Vec(-x, -y);
  42.     }
  43.     public Vec rotate(double theta) {
  44.         double sin = Math.sin(theta);
  45.         double cos = Math.cos(theta);
  46.         return new Vec(x*cos-y*sin,
  47.                        x*sin+y*cos);
  48.     }
  49.     public Vec normalize() {
  50.         double length=getLength();
  51.         if(length==0) return X_AXIS;
  52.         return new Vec(x/length, y/length);
  53.     }
  54.     public Vec add(Vec v) {
  55.         return new Vec(x+v.x, y+v.y);
  56.     }
  57.     public Vec sub(Vec v) {
  58.         return new Vec(x-v.x, y-v.y);
  59.     }
  60.     public Vec mul(double m) {
  61.         return new Vec(x*m, y*m);
  62.     }
  63.     public Vec div(double d) {
  64.         return new Vec(x/d, y/d);
  65.     }
  66.     public Vec neg() {
  67.         return new Vec(-x, -y);
  68.     }
  69.     public String toString() {
  70.         return String.format(java.util.Locale.ENGLISH,
  71.         "(%.3f, %.3f)", x, y);
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement