2015-04-04 132 views
1

我有一個矩形對象(sf::IntRect),其屬性爲:在2D平面上的左,上,寬和高。我想旋轉90度(即90,180或270)的倍數,圍繞點(0,0)。因此我寫一個函數是這樣的:將一個軸對齊的矩形旋轉90度

void rotateRect(sf::IntRect& rect, int rot) 
{ 
    //code I need 
} 

旋轉是0(0),1(90),2(180)或3(270)。

我該如何儘可能簡單地做到這一點。

+0

你嘗試過什麼嗎? –

+0

我對SFML不熟悉。它可能具有計算上述旋轉變換矩陣的函數。如果不是,他們非常簡單。請參閱http://en.wikipedia.org/wiki/Rotation_matrix。 –

+0

看看'sf :: Transform'。但是你確定要使用** Int ** Rect嗎? – Hiura

回答

0

下面是使用sf::Tranformsf::FloatRect鹼性溶液:

constexpr auto rotationAngle(int rot) { return rot * 90.f; } 

void rotateRect(sf::IntRect& rect, int rot) 
{ 
    auto deg = rotationAngle(rot); 
    auto transform = sf::Transform(); 
    transform.rotate(deg); 

    // Would be better if rect was a FloatRect... 
    auto rectf = sf::FloatRect(rect); 
    rectf = transform.transformRect(rectf); 
    rect = static_cast<sf::IntRect>(rectf); 
} 

不過,我個人會稍微改變你的函數使用float rects和更緊湊的符號的簽名:

sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot) 
{ 
    return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect); 
} 

下面是一個完整的例子,展示它的行爲。

#include <SFML/Graphics.hpp> 

constexpr auto rotationAngle(int rot) { return rot * 90.f; } 

sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot) 
{ 
    return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect); 
} 

void updateShape(sf::RectangleShape& shape, sf::FloatRect const& rect) 
{ 
    shape.setPosition(rect.left, rect.top); 
    shape.setSize({ static_cast<float>(rect.width), static_cast<float>(rect.height) }); 
} 

int main(int, char const**) 
{ 
    sf::RenderWindow window(sf::VideoMode(500, 500), "rotate"); 

    auto rect = sf::FloatRect(0, 0, 100, 50); 
    auto shape = sf::RectangleShape(); 
    shape.setFillColor(sf::Color::Red); 
    updateShape(shape, rect); 

    auto view = window.getView(); 
    view.move({ -250, -250 }); 
    window.setView(view); 

    while (window.isOpen()) 
    { 
     sf::Event event; 
     while (window.pollEvent(event)) 
     { 
      if (event.type == sf::Event::Closed) 
       window.close(); 

      if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::R) 
      { 
       rect = rotateRect(rect, 1); 
       updateShape(shape, rect); 
      } 

      if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::N) 
      { 
       rect = sf::FloatRect(50, 50, 100, 50); 
       updateShape(shape, rect); 
      } 

      if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::M) 
      { 
       rect = sf::FloatRect(0, 0, 100, 50); 
       updateShape(shape, rect); 
      } 
     } 

     window.clear(); 
     window.draw(shape); 
     window.display(); 
    } 

    return EXIT_SUCCESS; 
} 

注意:我使用了一些技巧從C++ 14,但我敢肯定,你可以在代碼轉換爲C++ 11/C++ 98,如果你需要。