Skip to content

Instantly share code, notes, and snippets.

@MichaelEstes
Last active August 29, 2015 14:06
Show Gist options
  • Save MichaelEstes/cccf56def3e162a0b37d to your computer and use it in GitHub Desktop.
Save MichaelEstes/cccf56def3e162a0b37d to your computer and use it in GitHub Desktop.
2D Rectangle Class in C++, includes collision detection (Header and CPP file)
#include "vector.h"
#include "circle.h"
using namespace std;
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle2D{
public:
const int numPoints = 4;
float width, height;
gVector2 topLeft, rectPoints[4];
Rectangle2D() : topLeft(0, 0), width(1), height(1){}
Rectangle2D(gVector2 topL, float w, float h) : topLeft(topL), width(w), height(h){}
gVector2 GetTopRight()const{ return gVector2(topLeft.x + width, topLeft.y); }
gVector2 GetBottomLeft()const{ return gVector2(topLeft.x, topLeft.y + height); }
gVector2 GetBottomRight()const{ return gVector2(topLeft.x + width, topLeft.y + height); }
float Area()const{ return width * height; }
float Perimeter()const{ return 2 * Area(); }
float Diagonal()const { return sqrt((width * width) + (height * height)); }
void SetPoints();
bool PointCollision(gVector2)const;
bool RectCollision(Rectangle2D)const;
bool CircleCollision(Circle2D);
};
#endif
#include "rectangle.h"
using namespace std;
void Rectangle2D::SetPoints(){
rectPoints[0] = topLeft;
rectPoints[1] = GetTopRight();
rectPoints[2] = GetBottomLeft();
rectPoints[3] = GetBottomRight();
}
bool Rectangle2D::PointCollision(gVector2 point)const{
gVector2 max = GetBottomRight();
return (point.x < max.x && point.x > topLeft.x &&
point.y < max.y && point.y > topLeft.y);
}
bool Rectangle2D::RectCollision(Rectangle2D rectB)const{
gVector2 maxA, maxB;
maxA = GetBottomRight();
maxB = rectB.GetBottomRight();
return (rectB.topLeft.x < maxA.x &&
maxB.y > topLeft.y);
}
bool Rectangle2D::CircleCollision(Circle2D circle){
gVector2 point;
SetPoints();
for (int i = 0; i < numPoints; ++i){
point = rectPoints[i];
point.x = point.x - circle.center.x;
point.x *= point.x;
point.y = point.y - circle.center.y;
point.y *= point.y;
if (point.x + point.y < circle.radius * circle.radius){
return true;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment