Following from my previous blog post on how I made a vector library, this post will be about some of the changes I made.
There was a few changes I wanted to make, primarily in regards to how functions were called. Previously, to call a vector related function, you had to use an already made variable like so:
Vector2<int> vectorVariable;
float mag = vectorVariable.Magnitude(someVector,someOtherVector);
You can see here that the function is getting the magnitude of two completely unrelated variables, but had to be called from an already made variable. Thankfully my lecturer pointed me towards making static functions, which could be called without an instance of the class.
So this code:
Vector2<T> Magnitude(const Vector2<T>& vec1, const Vector2<T>& vec2) const;
Became this:
static T Magnitude(const Vector2<T>& vec1, const Vector2<T>& vec2);
The resulting code means that I could call a function using the class type:
float mag = Vector2<float>::Magnitude(someVar1,someVar2);
Or I could use the typnames in the place of manually inputting the type.
The next thing I did, was update how to call Dot product and Cross product. Previously I chose to use operators because I didn’t know about using static functions, and so I thought it was unwieldy. Now that the function can be called without a variable, I converted them into functions, the result being this:
template <typename T>
T Vector2<T>::Dot(const Vector2<T>& vec1, const Vector2<T>& vec2)
{
return (vec1.x * vec2.x) + (vec1.y * vec2.y);
}template <typename T>
T Vector2<T>::Cross(const Vector2<T>& vec1, const Vector2<T>& vec2)
{
return (vec1.x * vec2.y) – (vec2.x * vec1.y);
}
I also made sure that the type being returned is generic as well, incase someone wants to pass in a double instead of a float.
I also updated the magnitude overload functions. The user now has a choice of three methods of using magnitude:
T Magnitude() const;//magnitude of this vector from 0,0
static T Magnitude(const Vector2<T>& other);//magnitude a target vector from 0,0
static T Magnitude(const Vector2<T>& vec1, const Vector2<T>& vec2);//magnitude of two points
And updated Normalise(d) to do the same thing
//normalise vector
void Normalise();
Vector2<T> Normalised() const;
static void Normalise(Vector2<T>& other);
static Vector2<T> Normalised(const Vector2<T>& other);