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 781 times)

0 Members and 1 Guest are viewing this topic.

TrickyWidget

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

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);
        Line.setPosition(StartPoint);
        Line.setRotation(Angle);
        Line.setFillColor(LineColor);

        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 »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10819
    • 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/

Hapax

  • Hero Member
  • *****
  • Posts: 3351
  • 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):
https://github.com/Hapaxia/SelbaWard/commit/fd0c276d7b710d8b14e1a806514166e5af27821a#diff-03ac2db8750e69ad3624f516374fac6000780016b10ccef99d2afa09733bd05aR146-R156
but I ended up changing it to a vertex array for consistency with the rest of Selba Ward (especially Spline).
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*