Elements used in the Balls and Things games for the RETRO.
Dependents: RETRO_BallsAndPaddle RETRO_BallAndHoles
Vector.cpp
- Committer:
- maxint
- Date:
- 2015-02-25
- Revision:
- 2:74bc9b16fb88
- Parent:
- 0:3d0db4e183ee
File content as of revision 2:74bc9b16fb88:
#include "Vector.h" Vector::Vector() { // constructor this->set((float)0,(float)0); } Vector::Vector(float fX, float fY) { this->set(fX, fY); } void Vector::set(float fX, float fY) { x=fX; y=fY; } void Vector::set(int nX, int nY) { this->set((float)nX, (float)nY); } float Vector::getSize() { // get the size of the vector return(sqrt(x*x+y*y)); } bool Vector::isLeft() { return(x<0); } bool Vector::isRight() { return(x>0); } bool Vector::isUp() { return(y<0); } bool Vector::isDown() { return(y>0); } void Vector::add(float fAdd) { // add the size of the vector by adding to its size float fSize=getSize(); float fSizeNew=fSize+fAdd; if(fSize!=0) { x=x * (fSizeNew/fSize); y=y * (fSizeNew/fSize); } else { // in case of zero lenght, default to addition in first quadrant. x=sqrt(0.5 * fAdd * fAdd); y=x; } } void Vector::add(Vector vAdd) { x+=vAdd.x; y+=vAdd.y; } void Vector::multiply(Vector vMult) { // 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); }