I wrote code to draw a circle segment, such that the segment angle will be facing the mouse.
My code:
#include <SFML/Graphics.hpp>
#include <math.h>
const float PI{ 3.14159265359f };
//convert degress to radians
float degToRad(float deg)
{
return
deg * PI / 180;
}
void drawCircleSegment(sf::RenderWindow & gameWindow)
{
gameWindow.clear();
sf::VertexArray arr(sf::LinesStrip);
float segmentAngle{degToRad(45)};
float radius{100};
sf::Vector2f radiusPos{ gameWindow.getView().getCenter() };
unsigned circlePoints{20};
float angle{ 0 };
arr.append(radiusPos);
do
{
sf::Vector2f mRelP //get relative mouse position
{
sf::Mouse::getPosition(gameWindow).x - radiusPos.x,
sf::Mouse::getPosition(gameWindow).y - radiusPos.y
};
float mouseAngle{ atan2(mRelP.y, mRelP.x) }; //get angle between relative mouse position and circle center
sf::Vector2f p
{
cos(angle + (mouseAngle - segmentAngle / 2)) * radius, //position = cos(angle + lookAngle) * rad
sin(angle + (mouseAngle - segmentAngle / 2)) * radius //position = sin(angle + lookAngle) * rad
};
p += radiusPos;
arr.append(p);
angle += segmentAngle / circlePoints;
} while (angle < segmentAngle);
arr.append(radiusPos);
gameWindow.draw(arr);
gameWindow.display();
}
int main()
{
sf::RenderWindow gameWindow(sf::VideoMode(800, 600), "circle");
gameWindow.setFramerateLimit(60);
while (gameWindow.isOpen())
{
sf::Event event;
while (gameWindow.pollEvent(event))
if (event.type == sf::Event::Closed)
gameWindow.close();
drawCircleSegment(gameWindow);
}
}
What do you think about it?