Search code examples
c++sfml

Is there a way to rotate an sf::FloatRect


I'm making a collision detection system in my project, and I need to detect collisions on a rotated texture.

To detect to collisions, 4 sf::FloatRect objects are made around the main character texture (for detecting collision to the left, right, up and down), and a sf::FloatRect is made using the position of a texture and it's dimentions. If one of the 4 sf::FloatRect objects around the main texture intersect the other sf::FloatRect, a collision is detected.

The problem comes when the texture on which I want to detect collision is rotated. The sf::FloatRect does not rotate.

Is there a way to rotate it? Or is there a substitute for it in this situation? I looked through the online documentation for SFML and I couldn't find any way to rotate it.

    RectangleShape collisionArea(Vector2f(pos[2], pos[3]));
    collisionArea.setPosition(pos[0], pos[1]);
    collisionArea.setRotation(rotation);

    FloatRect box = collisionArea.getGlobalBounds();


        FloatRect areaLeft(position.x - movementSpeed, position.y, movementSpeed, textureDimentions.y);
        FloatRect areaRight(position.x + textureDimentions.x, position.y, movementSpeed, textureDimentions.y);
        FloatRect areaUp(position.x, position.y - movementSpeed, textureDimentions.x, movementSpeed);
        FloatRect areaDown(position.x, position.y + textureDimentions.y, textureDimentions.x, movementSpeed);

        if(box.intersects(areaLeft))
        {
            collidingMap[0] = true;
        }

        if(box.intersects(areaRight))
        {
            collidingMap[1] = true;
        }


        if(box.intersects(areaUp))
        {
            collidingMap[2] = true;
        }


        if(box.intersects(areaDown))
        {
            collidingMap[3] = true;
        }

Solution

  • sf::FloatRect in SFML represents an AABB (AABB stands for Axis-Aligned Bounding Box). So no, it cannot rotate. What you need is OBB (Oriented Bounding Box) collision detection. You're gonna need to either

    • Write your own code for it (difficult)

    or

    • Find a library that does the job for you !

    I found this after searching on the SFML forum. There may be better solutions than this but this is the first one I found.