Elements used in the Balls and Things games for the RETRO.

Dependents:   RETRO_BallsAndPaddle RETRO_BallAndHoles

Revision:
2:74bc9b16fb88
Parent:
0:3d0db4e183ee
--- a/Vector.cpp	Fri Feb 06 10:18:02 2015 +0000
+++ b/Vector.cpp	Wed Feb 25 10:43:15 2015 +0000
@@ -57,4 +57,49 @@
 {   // multiply the vector by means of the other vector
     x*=vMult.x;
     y*=vMult.y;
+}
+
+Vector Vector::getNormalized()
+{   // get the Unit vector (= vector normalized to length 1)
+    // see http://en.wikipedia.org/wiki/Unit_vector
+    return(Vector(x/getSize(), y/getSize()));
+}
+
+Vector Vector::getNormal()
+{   // get the normal Vector
+    // see http://stackoverflow.com/questions/14885693/how-do-you-reflect-a-vector-over-another-vector
+    // vec.leftNormal --> vx = vec.vy; vy = -vec.vx; 
+    // vec.rightNormal --> vx = -vec.vy; vy = vec.vx;
+    if(isLeft())
+        return(Vector(y, -1 * x));
+    else
+        return(Vector(-1 * y, x));
+}
+    
+void Vector::bounce(Vector vBounce)
+{   // bounce a vector against another vector
+    // see http://stackoverflow.com/questions/14885693/how-do-you-reflect-a-vector-over-another-vector
+    Vector vBounceNormalized=vBounce.getNormalized();
+    Vector vBounceNormal=vBounce.getNormal();
+    Vector vBounceNormalNormalized=vBounceNormal.getNormalized();
+
+    // 1. Find the dot product of vec1 and vec2
+    // Note: dx and dy are vx and vy divided over the length of the vector (magnitude)
+    float dpA = x * vBounceNormalized.x + y * vBounceNormalized.y;
+
+    // 2. Project vec1 over vec2
+    float prA_vx = dpA * vBounceNormalized.x;
+    float prA_vy = dpA * vBounceNormalized.y;
+
+    // 3. Find the dot product of vec1 and vec2's normal
+    float dpB = x * vBounceNormalNormalized.x + y * vBounceNormalNormalized.y;
+
+    // 4. Project vec1 over vec2's left normal
+    float prB_vx = dpB * vBounceNormalNormalized.x;
+    float prB_vy = dpB * vBounceNormalNormalized.y;
+
+    // 5. Add the first projection prA to the reverse of the second -prB
+    float new_vx = prA_vx - prB_vx;
+    float new_vy = prA_vy - prB_vy;
+    set(new_vx, new_vy);
 }
\ No newline at end of file