下面是使用sf::Tranform
上sf::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,如果你需要。
你嘗試過什麼嗎? –
我對SFML不熟悉。它可能具有計算上述旋轉變換矩陣的函數。如果不是,他們非常簡單。請參閱http://en.wikipedia.org/wiki/Rotation_matrix。 –
看看'sf :: Transform'。但是你確定要使用** Int ** Rect嗎? – Hiura