game/sdlpp/sdlpp_collision.cpp

94 lines
3.0 KiB
C++

#include "sdlpp_collision.hpp"
#include "sdlpp_geometry.hpp"
namespace SDLPP {
CollisionPolygon::CollisionPolygon( double x, double y )
: CollisionPolygon( Vec2D< double >( x, y ) ) {}
CollisionPolygon::CollisionPolygon( const Vec2D< double > &input ) {
original = input;
position = { 0, 0 };
}
CollisionPolygon::CollisionPolygon( double x, double y, uint64_t id )
: CollisionPolygon( Vec2D< double >( x, y ), id ) {}
CollisionPolygon::CollisionPolygon( const Vec2D< double > &input, uint64_t id )
: CollisionPolygon( input ) {
_id = id;
}
bool CollisionPolygon::isInfinite() const {
return infinite;
}
void CollisionPolygon::setInfinite() {
infinite = true;
}
void CollisionPolygon::updateCollision( int x, int y, int w, int h,
uint64_t id ) {
if ( _id == static_cast< uint64_t >( -1 ) )
_id = id;
position = Vec2D< int >( original.getX() * w + x, original.getY() * h + y );
}
int CollisionPolygon::getX() const {
return position.getX();
}
int CollisionPolygon::getY() const {
return position.getY();
}
void CollisionPolygon::setColor( const std::string &color ) {
sdl_color = getSDLColorHEX( color );
}
void CollisionPolygon::setOutlineColor( const std::string &color ) {
sdl_outline = getSDLColorHEX( color );
}
void CollisionPolygon::setId( uint64_t id ) {
_id = id;
}
uint64_t CollisionPolygon::getId() {
return _id;
}
bool infinityIntersection( const SDLPP::CollisionPolygon &infinite,
const SDLPP::CollisionPolygon &other ) {
int ileft = infinite.leftmost();
int iright = infinite.rightmost();
int itop = infinite.topmost();
int ibottom = infinite.bottommost();
bool ret =
ileft != -1 && ileft <= other.rightmost() && ileft >= other.leftmost();
ret |= iright != -1 && iright >= other.leftmost() &&
iright <= other.rightmost();
ret |= itop != -1 && itop <= other.bottommost() && itop >= other.topmost();
ret |= ibottom != -1 && ibottom >= other.topmost() &&
ibottom <= other.bottommost();
ret |= ileft == -1 && iright == -1 && itop == -1 && ibottom == -1;
return ret;
}
bool intersects( const SDLPP::CollisionPolygon &p1,
const SDLPP::CollisionPolygon &p2 ) {
if ( p1.rightmost() < p2.leftmost() || p2.rightmost() < p1.leftmost() ||
p1.bottommost() < p2.topmost() || p2.bottommost() < p1.topmost() )
return false;
if ( p1.leftmost() < p2.leftmost() && p1.topmost() < p2.topmost() &&
p1.rightmost() > p2.rightmost() &&
p1.bottommost() > p2.bottommost() ) {
return true;
}
if ( p2.leftmost() < p1.leftmost() && p2.topmost() < p1.topmost() &&
p2.rightmost() > p1.rightmost() &&
p2.bottommost() > p1.bottommost() ) {
return true;
}
for ( auto &line : p1.getLines() ) {
for ( auto &line2 : p2.getLines() ) {
if ( linesCross( line, line2 ) )
return true;
}
}
return false;
}
} // namespace SDLPP