Vector2f.java :  » Graphics-3D-2D-OpenGL » glscene » org » glscene » geometry » Android Open Source

Android Open Source » Graphics 3D 2D OpenGL » glscene 
glscene » org » glscene » geometry » Vector2f.java
package org.glscene.geometry;

import java.nio.ByteBuffer;

import org.glscene.util.DirectBufferable;

public final class Vector2f implements DirectBufferable {
  
  private float fX, fY;
  
  public static final Vector2f NullVector = new Vector2f(0, 0);
  public static final Vector2f XVector = new Vector2f(1, 0);
  public static final Vector2f YVector = new Vector2f(0, 1);
  
  public Vector2f(float ax, float ay) {
    fX = ax;
    fY = ay;
  }
  
  public float getX() { return fX; }
  public float getY() { return fY; }
  
  public String toString() { 
    return "["+Float.toString(fX)+"; "+Float.toString(fY)+"]"; 
  }
  
  public void putInto(ByteBuffer buffer) {
    buffer.putFloat(fX);
    buffer.putFloat(fY);
  }
  
  public static Vector2f add (Vector2f a, Vector2f b) {
    return new Vector2f(a.fX+b.fX, a.fY+b.fY);
  }

  public static Vector2f sub (Vector2f a, Vector2f b) {
    return new Vector2f(a.fX-b.fX, a.fY-b.fY);
  }
  
  public static float dot (Vector2f a, Vector2f b) {
    return a.fX*b.fX+a.fY*b.fY;
  }
  
  public float length() {
    return (float) Math.sqrt((double) length2());
  }
  
  public float length2() {
    return fX*fX+fY*fY;
  }
  
  public Vector2f normalize() {
    float len = length();
    if (len>0) {
      float d = 1/len;
      return new Vector2f(fX*d, fY*d);
    } else {
      return NullVector; 
    }
  }

  public Vector2f adjustLength(float newLength) {
    float len = length();
    if (len>0) {
      float d = newLength/len;
      return new Vector2f(fX*d, fY*d);
    } else {
      return NullVector; 
    }
  }
  
  public Vector2f rotateRight90() {
    return new Vector2f(fY, -fX);
  }

  public Vector2f rotateLeft90() {
    return new Vector2f(-fY, fX);
  }
  
  public Vector2f scale(float f) {
    return new Vector2f(fX*f, fY*f);
  }
  
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.