Skip to content

Instantly share code, notes, and snippets.

@Hoekstraa
Last active August 30, 2021 20:47
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 Hoekstraa/c9611b9c928ffcdf818ebc326fe145ad to your computer and use it in GitHub Desktop.
Save Hoekstraa/c9611b9c928ffcdf818ebc326fe145ad to your computer and use it in GitHub Desktop.
Simple implementation of tavianator's branchless aabb->segment collision algo with SFML vectors
#include <cmath>
#include <SFML/Graphics.hpp>
struct AABB
{
sf::Vector2f origin;
sf::Vector2f size;
};
struct Segment
{
sf::Vector2f x0; //source
sf::Vector2f x1; //destination
sf::Vector2f n(){return x1 - x0;}; //direction
sf::Vector2f inverseDirection(){return {1 / n().x, 1 / n().y};};
};
bool intersection(AABB b, Segment r) {
double tx1 = (b.origin.x - r.x0.x) * r.inverseDirection().x;
double tx2 = ((b.origin.x + b.size.x) - r.x0.x) * r.inverseDirection().x;
double tmin = fmin(tx1, tx2);
double tmax = fmax(tx1, tx2);
double ty1 = (b.origin.y - r.x0.y) * r.inverseDirection().y;
double ty2 = ((b.origin.y + b.size.y) - r.x0.y) * r.inverseDirection().y;
tmin = fmax(tmin, fmin(ty1, ty2));
tmax = fmin(tmax, fmax(ty1, ty2));
return tmax >= tmin;
}
int main()
{
AABB r = {{100,100},{100,100}};
Segment s = {{50,50},{300,310}};
Segment nonIntersect = {{210,280},{210,290}};
puts(intersection(r, s)? "Yes" : "No");
puts(intersection(r, nonIntersect)? "Yes" : "No");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment