game/sdlpp/sdlpp_rectcolider.cpp

97 lines
3.1 KiB
C++

#include "sdlpp_rectcolider.hpp"
namespace SDLPP {
RectColider::RectColider( double x, double y, double w, double h )
: CollisionPolygon( x, y ) {
w_ = w;
h_ = h;
}
bool RectColider::colidesWith( const SDLPP::CollisionPolygon &other ) const {
if ( other.isCircle() ) {
return other.colidesWith( *this );
}
if ( other.isInfinite() ) {
return infinityIntersection( other, *this );
}
if ( isInfinite() )
return infinityIntersection( *this, other );
return intersects( *this, other );
}
bool RectColider::isCircle() const {
return false;
}
int RectColider::topmost() const {
return ( !isInfinite() || original_y != -1 ) * getY() + isInfinite() * -1;
}
int RectColider::bottommost() const {
return ( !isInfinite() || h_ != -1 ) * ( getY() + pixel_h ) +
isInfinite() * -1;
}
int RectColider::leftmost() const {
return ( !isInfinite() || original_x != -1 ) * getX() + isInfinite() * -1;
}
int RectColider::rightmost() const {
return ( !isInfinite() || w_ != -1 ) * ( getX() + pixel_w ) +
isInfinite() * -1;
}
void RectColider::updateCollision( int x, int y, int w, int h ) {
position_x = original_x * w + x;
position_y = original_y * h + y;
pixel_w = w_ * w;
pixel_h = h_ * h;
}
void RectColider::render( Renderer &renderer,
const std::tuple< int, int, int, int > &color ) {
auto rect = getRect();
// outline with desired color at 50% opacity
SDL_SetRenderDrawColor( renderer.getRendererPtr(), std::get< 0 >( color ),
std::get< 1 >( color ), std::get< 2 >( color ),
0x80 );
SDL_RenderDrawRect( renderer.getRendererPtr(), &rect );
// fill with desired color at 25% opacity
SDL_SetRenderDrawColor( renderer.getRendererPtr(), std::get< 0 >( color ),
std::get< 1 >( color ), std::get< 2 >( color ),
0x40 );
SDL_RenderFillRect( renderer.getRendererPtr(), &rect );
}
void RectColider::render( Renderer &renderer ) {
auto rect = getRect();
SDL_SetRenderDrawColor( renderer.getRendererPtr(), sdl_color.r, sdl_color.g,
sdl_color.b, sdl_color.a );
SDL_RenderFillRect( renderer.getRendererPtr(), &rect );
SDL_SetRenderDrawColor( renderer.getRendererPtr(), sdl_outline.r,
sdl_outline.g, sdl_outline.b, sdl_outline.a );
SDL_RenderDrawRect( renderer.getRendererPtr(), &rect );
}
SDL_Rect RectColider::getRect() {
if ( !isInfinite() )
return { leftmost(), topmost(), pixel_w, pixel_h };
SDL_Rect r = { 0, 0, 0, 0 };
if ( ( r.x = leftmost() ) == -1 )
r.x = 0;
if ( ( r.y = topmost() ) == -1 )
r.y = 0;
if ( rightmost() == -1 )
r.w = std::numeric_limits< int >::max();
else
r.w = pixel_w;
if ( bottommost() == -1 )
r.h = std::numeric_limits< int >::max();
else
r.h = pixel_h;
return r;
}
std::shared_ptr< CollisionPolygon > RectColider::copySelf() {
return std::make_shared< RectColider >( *this );
}
} // namespace SDLPP