Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Solved: How to do the math for a "line" with RectangleShape?  (Read 439 times)

0 Members and 1 Guest are viewing this topic.


  • Newbie
  • *
  • Posts: 1
    • View Profile
Solved: How to do the math for a "line" with RectangleShape?
« on: December 04, 2022, 03:08:24 am »

I was closer than I thought!  I finally figured it out.  Here's my code:

sf::RectangleShape MakeLine(sf::Vector2f StartPoint, sf::Vector2f EndPoint, sf::Color LineColor, float LineThickness)
        float VectorX = EndPoint.x - StartPoint.x;
        float VectorY = EndPoint.y - StartPoint.y;
        float Distance = sqrt((VectorX * VectorX) + (VectorY * VectorY));
        double Angle = atan2(VectorY, VectorX) * (180 / 3.14159265359);

        sf::RectangleShape Line(sf::Vector2f(Distance, LineThickness));
        Line.setOrigin(0.0, LineThickness / 2.0);

        return Line;


I'm trying to follow the advice to use RectangleShape to make lines (with thickness), but I'm stuck on the math.  I have the start and end points, but I don't know how to turn that into the length, position, and rotation of the rectangle.

Can anyone help me out?  Thanks!
« Last Edit: December 04, 2022, 03:33:14 pm by TrickyWidget »


  • SFML Team
  • Hero Member
  • *****
  • Posts: 10506
    • View Profile
    • development blog
    • Email
Re: Solved: How to do the math for a "line" with RectangleShape?
« Reply #1 on: December 06, 2022, 08:53:24 am »
There are also some ready-made implementations out there. For example on the wiki: https://github.com/SFML/SFML/wiki/Source%3A-Line-segment-with-thickness
Or as part of SelbaWard: https://github.com/Hapaxia/SelbaWard/wiki/Line
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
Dev Blog: https://duerrenberger.dev/blog/


  • Hero Member
  • *****
  • Posts: 3137
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Solved: How to do the math for a "line" with RectangleShape?
« Reply #2 on: December 20, 2022, 12:27:51 pm »
Fun fact: Selba Ward's Line did, in fact, initially just use a rectangle shape adjusted to fit the 2 points (here's the calculations I used - the highlighted section at the top):
but I ended up changing it to a vertex array for consistency with the rest of Selba Ward (especially Spline).
Selba Ward - SFML drawables
Kairos - Timing Library
Rectangular Boundary Collision - Rectangular SAT Collision

Hapaxia Links