/* vector2.c: Package for manipulating 2-dimensional vectors */ #include "vector2.h" /* For the vector structure declaration */ #include /* For sqrt, sin, cos & atan2 functions */ vector2 v2Add(vector2 a, vector2 b) { /* Sum of 2 vectors */ vector2 c; c.x = a.x + b.x; /* Adds the x components */ c.y = a.y + b.y; /* Adds the y components */ return c; } vector2 v2Sub(vector2 a, vector2 b) { /* Difference */ vector2 c; c.x = a.x - b.x; /* Subtracts the x components */ c.y = a.y - b.y; /* Subtracts the y components */ return c; } vector2 v2Neg(vector2 a) { /* Negative of vector */ a.x = -a.x; /* Negate x; this does not alter the actual parameter a */ a.y = -a.y; /* Negate y; this does not alter the actual parameter a */ return a; } vector2 sv2Mul(float f, vector2 v) { /* Multiply by a scalar */ v.x *= f; /* Multiply x by scalar; does not alter actual parameter */ v.y *= f; /* Multiply y by scalar; does not alter actual parameter */ return v; } float v2Len(vector2 v) { /* Length of vector */ return sqrt(v.x * v.x + v.y * v.y); /* Pythagoras' rule */ } /* (A better version of the function v2Len is given in chapter 16.) */ float v2Arg(vector2 v) { /* Angle of vector with x axis */ return atan2(v.y, v.x); /* Note: meaningless if v.y & v.x both zero */ } vector2 v2Polar(float len, float angle) { /* Compute vector from its length and direction */ vector2 v; v.x = len * cos(angle); v.y = len * sin(angle); return v; }