Browse Source

Vectors in C++: A quick look at Vec2.

Godzil 1 year ago
parent
commit
d32bbfb006
1 changed files with 14 additions and 6 deletions
  1. 14 6
      source/include/vec2.h

+ 14 - 6
source/include/vec2.h

@@ -54,20 +54,28 @@ struct vec2
     vec2 &normalise()
     {
         double m = this->magnitude();
-        this->x /= m;
-        this->y /= m;
+        if (m != 0.0)
+        {
+            this->x /= m;
+            this->y /= m;
+        }
+        return *this;
     };
     vec2 unitVector() const
     {
         double m = this->magnitude();
-        vec2 ret(this->x / m, this->y / m);
-
+        vec2 ret;
+        if (m != 0.0)
+        {
+            ret.x = this->x / m;
+            ret.y = this->y / m;
+        }
         return ret;
     };
     vec2 normal() const
     {
         vec2 ret(this->y, -this->x);
-        return ret;
+        return ret.normalise();
     };
 
     double dot(const vec2 &v) const
@@ -77,7 +85,7 @@ struct vec2
     double cross(const vec2 &v) const
     {
         /* return the imaginary Z component */
-        return this->x *  v.y - this->y * v.x;
+        return (this->x *  v.y) - (this->y * v.x);
     };
 };