Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created August 9, 2017 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonelbre/bf80ef86b3bebd06d0bf428d82418fa3 to your computer and use it in GitHub Desktop.
Save egonelbre/bf80ef86b3bebd06d0bf428d82418fa3 to your computer and use it in GitHub Desktop.
Shape Collision
#include "stdio.h"
#include "math.h"
#include "assert.h"
#define static_assert _Static_assert
typedef float f32;
typedef struct Vec2 { f32 X, Y; } Vec2;
float Vec2_Distance(Vec2 a, Vec2 b){
f32 dx = a.X - b.X;
f32 dy = a.Y - b.Y;
return sqrt(dx*dx + dy*dy);
}
enum ShapeType {
Shape_Circle,
Shape_AABB,
Shape_VerticalLine,
Shape_HorizontalLine,
ShapeCount
};
//TODO: ensure that this uses pow of 2
#define ShapePair(AType, BType) ((AType * ShapeCount) | BType)
struct Circle {
ShapeType Type;
Vec2 Center;
f32 Radius;
};
struct AABB {
ShapeType Type;
Vec2 Min, Max;
};
struct VerticalLine {
ShapeType Type;
Vec2 Start;
f32 Radius;
f32 Height;
};
struct HorizontalLine {
ShapeType Type;
Vec2 Start;
f32 Radius;
f32 Width;
};
struct Shape {
union {
struct {
ShapeType Type;
Vec2 Position;
};
struct Circle Circle;
struct AABB AABB;
struct VerticalLine VerticalLine;
struct HorizontalLine HorizontalLine;
};
};
bool Shapes_Colliding(Shape *a, Shape *b){
if(a->Type > b->Type){
Shape *t = b; b = a; a = t;
}
#define case_pair(aname, AType, bname, BType) \
case ShapePair(Shape_##AType, Shape_##BType): \
Shape *tmp_a = a; Shape *tmp_b = b; \
static_assert(Shape_##AType <= Shape_##BType, "order differently"); \
AType* aname = (AType*)tmp_a; \
BType* bname = (BType*)tmp_b;
switch ShapePair(a->Type, b->Type) {
{case_pair(a, Circle, b, Circle)
return Vec2_Distance(a->Center, b->Center) < a->Radius + b->Radius;
}
{case_pair(circle, Circle, aabb, AABB)
return Vec2_Distance(circle->Center, aabb->Min) < circle->Radius;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment