I have an axis-aligned bounding box (AABB) that I've coded, but at the moment it is very redundant. I feel like there are variables that I can get rid of. I need the AABB to be very fast, and I'd like it to be more lightweight than it is.
#pragma once
#include "Engine.h"
// Collision
#include "Vec2D.h"
// End Collision
#include "Renderer.h"
struct ENGINE_API AABB {
private:
Vec2D min;
Vec2D max;
double x;
double y;
double width;
double height;
double xwidth; // x + width
double yheight; // y + height
double vertMid; // vertical mid, cached for quadtree
double horzMid; // horizontal mid, cached for quadtree
// Normalize
void calcMid() {
vertMid = x + (width / 2);
horzMid = y + (height / 2);
xwidth = x + width;
yheight = y + height;
}
void init(Vec2D, Vec2D);
// End Normalize
public:
// Constructor
AABB(Vec2D min, Vec2D max) {
init(min, max);
}
AABB(double x, double y, double width, double height){
init(Vec2D(x, y), Vec2D(x + width, y + height));
}
// End Constructor
// Getters
double getX()const {
return x;
}
double getY()const {
return y;
}
double getWidth()const {
return width;
}
double getHeight()const {
return height;
}
double getHorzMid()const {
return horzMid;
}
double getVertMid()const {
return vertMid;
}
double getXWidth()const {
return xwidth;
}
double getYHeight()const {
return yheight;
}
// End Getters
// Base
bool collides(AABB other) {
if (xwidth < other.x || x > other.xwidth) { return false; }
if (yheight < other.y || y > other.yheight) { return false; }
return true;
}
bool contains(Vec2D point) {
if (x > point.getX() || xwidth < point.getX()) { return false; }
if (y > point.getY() || yheight < point.getY()) { return false; }
return true;
}
void move(double x, double y) {
this->x = x;
this->y = y;
calcMid();
}
// End Base
// Testing
void render(Renderer& renderer) {
sf::RectangleShape shape;
shape.setPosition(x, y);
shape.setOutlineColor(sf::Color::Red);
shape.setOutlineThickness(3);
shape.setSize(sf::Vector2f(width, height));
renderer.render(shape);
}
// End Testing
};
And the messy part:
void AABB::init(Vec2D one, Vec2D two) {
double x1 = one.getX();
double y1 = one.getY();
double xx = two.getX();
double yy = two.getY();
if (x1 > xx) {
if (y1 > yy) {
min = Vec2D(xx, yy);
max = Vec2D(x1, y1);
}
else {
min = Vec2D(xx, y1);
max = Vec2D(x1, yy);
}
}
else {
if (y1 > yy) {
min = Vec2D(x1, yy);
max = Vec2D(xx, y1);
}
else {
min = Vec2D(x1, y1);
max = Vec2D(xx, yy);
}
}
x = min.getX();
y = min.getY();
width = max.getX() - x;
height = max.getY() - y;
calcMid();
}
init
method. \$\endgroup\$ – ChrisW Mar 25 '14 at 17:08