Skip to content

Instantly share code, notes, and snippets.

@CairX
Created October 4, 2018 19:25
Show Gist options
  • Save CairX/0ee62ca63077ddadd1e90aa6623fb9ab to your computer and use it in GitHub Desktop.
Save CairX/0ee62ca63077ddadd1e90aa6623fb9ab to your computer and use it in GitHub Desktop.
#include <cmath>
#include <iostream>
struct vec {
float x, y;
vec(float x, float y) : x(x), y(y) {}
friend std::ostream& operator<<(std::ostream &os, const vec &v);
static float length(const vec &v) {
return sqrt(v.x * v.x + v.y * v.y);
}
static vec normalize(const vec &v) {
const auto l = vec::length(v);
return l > 0.0f ? v / l : v;
}
vec operator*(const float &scala) const {
return vec(this->x * scala, this->y * scala);
}
vec operator/(const float &scala) const {
return vec(this->x / scala, this->y / scala);
}
vec operator+(const vec &other) const {
return vec(this->x + other.x, this->y + other.y);
}
vec operator-(const vec &other) const {
return vec(this->x - other.x, this->y - other.y);
}
};
std::ostream& operator<<(std::ostream &os, const vec &v) {
os << v.x << ", " << v.y;
return os;
}
struct rect {
vec pos, dim;
rect(float x, float y, float w, float h) :
pos(x, y), dim(w, h) {}
float left() const { return pos.x; }
float right() const { return pos.x + dim.x; }
float top() const { return pos.y; }
float bottom() const { return pos.y + dim.y; }
vec center() const { return (pos + dim) * 0.5f; }
};
bool overlapping(const rect &a, const rect &b) {
return !(
a.left() > b.right() ||
a.right() < b.left() ||
a.top() > b.bottom() ||
a.bottom() < b.top()
);
}
void collision(const rect &a, const rect &b) {
auto o = overlapping(a, b);
std::cout << "collision: " << (o ? "true" : "false") << "\n";
auto n = vec::normalize(a.pos - b.pos);
std::cout << "normalized: " << n << "\n";
}
int main() {
rect t1(0.0f, 0.0f, 10.0f, 10.0f);
rect t2(11.0f, 0.0f, 10.0f, 10.0f);
rect t3(9.0f, 9.0f, 10.0f, 10.0f);
collision(t1, t1);
collision(t1, t2);
collision(t1, t3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment