Exemple #1
0
sf::IntRect Collision::GetAABB(const sf::Sprite& Object) {

    //Get the top left corner of the sprite regardless of the sprite's center
    //This is in Global Coordinates so we can put the rectangle back into the right place
    sf::Vector2f pos = Object.TransformToGlobal(sf::Vector2f(0, 0));

    //Store the size so we can calculate the other corners
    sf::Vector2f size = Object.GetSize();

    float Angle = Object.GetRotation();

    //Bail out early if the sprite isn't rotated
    if (Angle == 0.0f) {
        return sf::IntRect(static_cast<int> (pos.x),
                static_cast<int> (pos.y),
                static_cast<int> (pos.x + size.x),
                static_cast<int> (pos.y + size.y));
    }

    //Calculate the other points as vectors from (0,0)
    //Imagine sf::Vector2f A(0,0); but its not necessary
    //as rotation is around this point.
    sf::Vector2f B(size.x, 0);
    sf::Vector2f C(size.x, size.y);
    sf::Vector2f D(0, size.y);

    //Rotate the points to match the sprite rotation
    B = RotatePoint(B, Angle);
    C = RotatePoint(C, Angle);
    D = RotatePoint(D, Angle);

    //Round off to int and set the four corners of our Rect
    int Left = static_cast<int> (MinValue(0.0f, B.x, C.x, D.x));
    int Top = static_cast<int> (MinValue(0.0f, B.y, C.y, D.y));
    int Right = static_cast<int> (MaxValue(0.0f, B.x, C.x, D.x));
    int Bottom = static_cast<int> (MaxValue(0.0f, B.y, C.y, D.y));

    //Create a Rect from out points and move it back to the correct position on the screen
    sf::IntRect AABB = sf::IntRect(Left, Top, Right, Bottom);
    AABB.Offset(static_cast<int> (pos.x), static_cast<int> (pos.y));
    return AABB;
}