UdK - Principles of computational design
   
     
 

Introduction to vector maths

[The examples here pertain to 2D vectors. Check the Vec3D library for 3D vectors.]

A point has only one property: A location in space. A vector has two properties: A length and a direction. A vector is not a line, it is an indication of direction or force.

Vectors are used for a multitude of tasks in computer graphics and computation related to spaces. It is also used in physics to represent forces working on objects, such as magnetism or friction. Vectors are essential to modelling motion.


Simple vector maths

The vector from x1,y2 to x2,y2 = <x2-x1,y2-y1>

Given that:

xD=x2-x1
yD=y2-y1


Then angle between x1,y1 and x2,y2 is:

angle=atan2(yD,xD)


The distance between <x1,y1> and <x2,y2> is:

distance=sqrt(xD*xD+yD*yD)


A vector of length 1 is called a normalised vector. A normalised vector with the same direction as the vector between <x1,y1> and <x2,y2> is obtained as follows:

<xD/distance, yD/distance>


A tangent vector to <xD,yD> (a vector rotated 90 degrees to the <xD,yD> vector) will be:

<-yD, xD>


Adding, subtracting, multiplying and dividing vectors is done as follows:

<vecx1, vecy1> + <vecx2, vecy2> = <vecx1 + vecx2, vecy1 + vecy2>

<vecx1, vecy1> - <vecx2, vecy2> = <vecx1 - vecx2, vecy1 - vecy2>

<vecx1, vecy1> * 5 = <vecx1 * 5, vecy1 * 5>

<vecx1, vecy1> / 5 = <vecx1 / 5, vecy1 / 5>


Rotation of a vector is done as follows:

<x, y> rotated by PI is <x * cos(PI) - y * sin(PI), x * sin(PI) + y * cos(PI)>

 

Universität der Künste, Berlin 2003 - Marius Watz
 

Other sources

There is a comprehensive tutorial on vectors at the Central Connecticut State University site for Computer Science.

Vec2D library

I have made a simple 2D vector library as a class for Processing. Copy it into your files to use it:

// General vector class for 2D vectors
class Vec2D {
  float x,y;

  Vec2D(float _x,float _y) {
    x=_x;
    y=_y;
  }

  Vec2D(Vec2D v) {
    x=v.x;
    y=v.y;
  }

  void set(float _x,float _y) {
    x=_x;
    y=_y;
  }

  void set(Vec2D v) {
    x=v.x;
    y=v.y;
  }

  void add(float _x,float _y) {
    x+=_x;
    y+=_y;
  }

  void add(Vec2D v) {
    x+=v.x;
    y+=v.y;
  }

  void sub(float _x,float _y) {
    x-=_x;
    y-=_y;
  }

  void sub(Vec2D v) {
    x-=v.x;
    y-=v.y;
  }

  void mult(float m) {
    x*=m;
    y*=m;
  }

  void div(float m) {
    x/=m;
    y/=m;
  }

  float length() {
    return sqrt(x*x+y*y);
  }

  float angle() {
    return atan2(y,x);
  }

  void normalise() {
    float l=length();
    if(l!=0) {
      x/=l;
      y/=l;
    }
  }

  Vec2D tangent() {
    return new Vec2D(-y,x);
  }

  void rotate(float val) {
    // Due to float not being precise enough, double is used for the calculations
    double cosval=Math.cos(val);
    double sinval=Math.sin(val);
    double tmpx=x*cosval - y*sinval;
    double tmpy=x*sinval + y*cosval;

    x=(float)tmpx;
    y=(float)tmpy;
  }
}