I have a set of vertices that I need to rotate in an angle Θ around a pivot, but when I apply the transformation the vertices are distorted. What's going on wrong? I got the answer formula from a similar question in this post
Here's my code:
#include <SFML/Graphics.hpp>
#include <cmath>
#define PI 3.14159265359f
using namespace std;
sf::VertexArray vertexRotate(sf::VertexArray &toRotate, float theta, sf::Vector2f &pivot);
sf::VertexArray vertexTranslate(sf::VertexArray &toTranslate, float x, float y);
sf::VertexArray vertexRotate(sf::VertexArray &toRotate, float theta, sf::Vector2f &pivot = sf::Vector2f(0,0)) {
sf::VertexArray vertexCopy(toRotate);
for (int i = 0; i < vertexCopy.getVertexCount(); i++) {
vertexCopy[i].position.x = pivot.x + (vertexCopy[i].position.x - pivot.x) * cos(theta) - (vertexCopy[i].position.y - pivot.y) * sin(theta);
vertexCopy[i].position.y = pivot.y + (vertexCopy[i].position.x - pivot.x) * sin(theta) + (vertexCopy[i].position.y - pivot.y) * cos(theta);
}
return vertexCopy;
}
sf::VertexArray vertexTranslate(sf::VertexArray &toTranslate, float x, float y) {
sf::VertexArray vertexCopy(toTranslate);
for (int i = 0; i < vertexCopy.getVertexCount(); i++) {
vertexCopy[i].position.x += x;
vertexCopy[i].position.y += y;
}
return vertexCopy;
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Linear Algebra");
sf::VertexArray nave(sf::PrimitiveType::Points, 4);
nave[0].position = sf::Vector2f(100, 100);
nave[1].position = sf::Vector2f(130, 10);
nave[2].position = sf::Vector2f(130, 80);
nave[3].position = sf::Vector2f(160, 100);
for (int i = 0; i < nave.getVertexCount(); i++)
nave[i].color = sf::Color::White;
sf::Transform t;
t.rotate(90);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(nave);
auto nave2 = vertexRotate(nave, PI/2);
nave2 = vertexTranslate(nave2, 300, 300);
window.draw(nave2);
window.display();
}
return 0;
}