SFML community forums
Help => Graphics => Topic started by: reDo on September 16, 2011, 08:45:53 pm
-
Is there any way how can I get positions of my 4 points of my picture when it is rotated from SFML please? because I am currently doing stuff around collision detection rotated rectangles and I need these points. :roll:
-
Yes, you need to translate the sprite to the origin of the coordinate system, then multiply the position of each point with a 2D rotation matrix:
http://en.wikipedia.org/wiki/Rotation_matrix
and translate each point back the same direction and distance that you translated it when translating to the origin.
All of that is assuming that your sprite rotates around its center.
-
But I am asking, is some way how to get coordinates of these four points directly through SFML? I dont understand how to use that rotation matrix, so I will try to make it with sin and cos. :)
-
You must use the TransformToGlobal function to transform the 4 corners of the sprite by its position/rotation/scale. The 4 corners are defined by the subrect of the sprite.
-
I tried this but after few pressed arrows my rect1(picture that I need to check collision) was gone from the screen. :(
rect1.png = R1 is normal picture 100x200.
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <cmath>
typedef sf::Vector2f VECTOR;
VECTOR rect1[4] = {VECTOR(400,200),VECTOR(500,200),VECTOR(500,400),VECTOR(400,400)};
//VECTOR rect2[4] = {VECTOR(350,200),VECTOR(450,200),VECTOR(450,400),VECTOR(350,400)};
void DrawRect(sf::RenderWindow & App, const VECTOR rect[], int r, int g, int b)
{
for(int i=0;i<4;i++)
App.Draw(sf::Shape::Line(rect[i].x,rect[i].y,
rect[i+(i==3? -3 : 1)].x,rect[i+(i==3? -3 : 1)].y,1,sf::Color(r,g,b)));
}
int main()
{
sf::RenderWindow App(sf::VideoMode(800,600,32),"Vector");
sf::Texture imgR1;
imgR1.LoadFromFile("rect1.png");
imgR1.SetSmooth(false);
sf::Sprite R1(imgR1);
R1.SetPosition(200,200);
R1.SetOrigin(0,0);
int angle=0;
R1.SetRotation(angle);
App.SetFramerateLimit(60);
while(App.IsOpened())
{
sf::Event Event;
App.PollEvent(Event);
if(Event.Type == sf::Event::Closed)
App.Close();
if(Event.Key.Code == sf::Keyboard::Escape)
App.Close();
if((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Keyboard::Right))
{
R1.SetRotation(angle--);
rect1[0] = R1.TransformToGlobal(rect1[0]);
rect1[1] = R1.TransformToGlobal(rect1[1]);
rect1[2] = R1.TransformToGlobal(rect1[2]);
rect1[3] = R1.TransformToGlobal(rect1[3]);
}
if((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Keyboard::Left))
{
R1.SetRotation(angle++);
rect1[0] = R1.TransformToGlobal(rect1[0]);
rect1[1] = R1.TransformToGlobal(rect1[1]);
rect1[2] = R1.TransformToGlobal(rect1[2]);
rect1[3] = R1.TransformToGlobal(rect1[3]);
}
App.Clear();
DrawRect(App,rect1,255,0,0);
App.Draw(R1);
App.Display();
}
return 0;
}