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

Dependents:   RETRO_BallsAndPaddle RETRO_BallAndHoles

Revision:
3:441dc90d10ce
Parent:
0:3d0db4e183ee
Child:
4:f421e34313d3
--- a/Shapes.cpp	Wed Feb 25 10:43:15 2015 +0000
+++ b/Shapes.cpp	Thu Feb 26 11:46:46 2015 +0000
@@ -36,6 +36,73 @@
 
 
 ///////////////////
+// LINE
+///////////////////
+
+Line::Line(int x,int y, int xx, int yy)
+{
+    x1 = x;
+    x2 = xx;
+    y1 = y;
+    y2 = yy;
+}
+
+Line::Line(Point p1, Point p2)
+{
+    x1 = p1.getX();
+    x2 = p2.getX();
+    y1 = p1.getY();
+    y2 = p2.getY();
+}
+
+Point Line::get1()
+{
+    return(Point(x1, y1));
+}
+
+Point Line::get2()
+{
+    return(Point(x2, y2));
+}
+
+
+float Line::getSizeFloat()
+{   // get the size of the vector
+    return(sqrt((float)(x2-x1)*(float)(x2-x1)+(float)(y2-y1)*(float)(y2-y1)));
+}
+
+int Line::getSize()
+{   // get the size of the vector
+    return((int)getSizeFloat());
+}
+
+Rectangle Line::getBoundingRectangle()
+{
+    return(Rectangle(x1, y1, x2, y2));
+}
+
+int Line::getDistance(Point pt)
+{   // get the distance of a line to a point
+    //TODO
+    Line ln1(get1(), pt);
+    Line ln2(get2(), pt);
+    int nDist1=ln1.getSize();
+    int nDist2=ln2.getSize();
+    int nDistApprox=nDist1+nDist2-getSize();
+    
+    // simple distance calculation:
+    //    if distance to either line-end combined equal to the line-length, the point is on the line
+    //    if the point is nearby, the difference might be good approximation of the distance
+    if(nDistApprox<nDist1 && nDistApprox<nDist2)
+        return(nDistApprox);
+    
+    return(MIN(nDist1,nDist2));
+}
+
+
+
+
+///////////////////
 // RECTANGLE
 ///////////////////
 
@@ -225,3 +292,30 @@
 {
     return(Rectangle(x1-r1, y1-r1, x1+r1, y1+r1));
 }
+
+bool Circle::collides(Line ln)
+{   // see if a circle collides with a line
+    // check 1: first check using bounding rectangles
+    // check 2: distance of line-ends to center or circle
+    // check 3: check if distance to line is smaller than radius
+    
+    // Simple check 1:  using bounding rectangles
+    Rectangle rCircle=getBoundingRectangle();
+    if(!rCircle.collides(ln.getBoundingRectangle()))
+        return(false);
+    
+    // Simple check 2: distance of line-ends to center or circle
+    Point ptCenter=getCenter();
+    Line lnA(ptCenter, ln.get1());
+    if(lnA.getSize()<=r1)
+        return(true);
+    Line lnB(ptCenter, ln.get2());
+    if(lnB.getSize()<=r1)
+        return(true);
+
+    // check 3: check if distance to line is smaller than radius
+    if(ln.getDistance(ptCenter) <= r1)
+        return(true);
+
+    return(false); 
+}