ELEC2645 (2018/19) / Mbed 2 deprecated el17dg

Dependencies:   mbed

Fork of el17dg by Dmitrijs Griskovs

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers collision_lib.h Source File

collision_lib.h

00001 #ifndef COLLISION_LIB_H
00002 #define COLLISION_LIB_H
00003 
00004 #include <math.h>
00005 
00006 /**
00007  * @struct Point
00008  * @brief Position or vector on the screen. Supports basic vector arithmetics.
00009  */
00010 struct Point {
00011     /*@{*/
00012     int x; /**< the x position */
00013     int y; /**< the y position */
00014     /** Default constructor */
00015     Point() : x(0), y(0) {}
00016     /** Constructor with x and y parameters */
00017     Point(int _x, int _y) : x(_x), y(_y) {}
00018     
00019     /** 
00020      * @brief Vector addition. 
00021      */
00022     Point operator+ (const Point& rhs) const {
00023         Point result(x + rhs.x, y + rhs.y);
00024         return result;
00025     }
00026 
00027     /** 
00028      * @brief Vector substraction. 
00029      */
00030     Point operator- (const Point& rhs) const {
00031         Point result(x - rhs.x, y - rhs.y);
00032         return result;
00033     }
00034     
00035     /** 
00036      * @brief Length of vector squared. 
00037      */
00038     int lengthSquared() {
00039         return x * x + y * y;
00040     }
00041 };
00042 
00043 /** 
00044  * CicleBounds Class
00045  * @brief Class to define object's bounds as a circle with center(e.g. offset).
00046  * @author Dmitrijs Griskovs
00047  * @date 15/04/2019
00048  */
00049 class CircleBounds {
00050 public:
00051     /** Default constructor */
00052     CircleBounds() {};
00053     /** Constructor with center and radius parameters */
00054     CircleBounds(Point _center, float _radius): center(_center), radius(_radius) {};
00055     Point center;
00056     float radius;
00057 };
00058 
00059 /** 
00060  * @brief Determines whether the two circles collide.
00061  * @details the function takes in position and circle bounds (center and radius)
00062  * of two objects and returns wether they collided.
00063  *
00064  * @param pos_a positon of x and y of the first object. (const Point&).
00065  * @param bounds_a center point and radius of the first object. (const CircleBounds&).
00066  * @param pos_b positon of x and y of the second object. (const Point&).
00067  * @param bounds_b center point and radius of the second object. (const CircleBounds&).
00068  * @return true if the two circles overlap.
00069  */
00070 inline bool circleCollideTwoObjects(
00071     const Point& pos_a, const CircleBounds& bounds_a, 
00072     const Point& pos_b, const CircleBounds& bounds_b
00073 ) {
00074     Point center_a = pos_a + bounds_a.center;
00075     Point center_b = pos_b + bounds_b.center;
00076     Point difference = center_a - center_b;
00077     return difference.lengthSquared() <= pow(bounds_a.radius + bounds_b.radius, 2);
00078 }
00079 
00080 #endif