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

Author Topic: [SOLVED] What Is Wrong With This Line Algorithm?  (Read 165 times)

0 Members and 1 Guest are viewing this topic.

SkeleDotCpp

  • Newbie
  • *
  • Posts: 12
    • View Profile
[SOLVED] What Is Wrong With This Line Algorithm?
« on: May 17, 2019, 02:43:02 am »
I am trying to make a function that draws a line from a point to another.
Here is what I have:
const double PI = 3.14159265;

//Line shape
void line(sf::RenderWindow &win, int ax, int ay, int bx, int by) {
        //Angle
        int xDist = bx - ax;
        int yDist = by - ay;
        int length = sqrt((xDist * xDist) + (yDist * yDist)); //c = sqrt(a^2 + b^2)
        float angle = atan2(yDist, xDist) * 180 / PI; //Get angle and convert into degrees

        //Draw a rectangle as the line
        sf::RectangleShape line;
        line.setSize(sf::Vector2f(length, 3));
        line.setOrigin(0, line.getSize().y / 2); //Set the origin of the rectangle at left-middle
        line.setRotation(angle); //Rotate the rectangle by the angle calculated

        //Draw the rectangle
        win.draw(line);
}

And when I call it like so, it works perfectly fine:
line(window, 0, 0, mouseX, mouseY);

Note: mouseX, and mouseY are both defined prior.

But the problem is that when I call it like so, I get the line flipped by 180 degrees:
line(window, mouseX, mouseY, 0, 0);

And if I set the rotation by the angle + 180, it works fine, until I go back to the first method of calling it
(0,0, mouseX, mouseY)

Which now produces the line flipped by 180 degrees.

What exactly is the problem with the algorithm?
« Last Edit: May 18, 2019, 02:16:39 am by SkeleDotCpp »

FRex

  • Hero Member
  • *****
  • Posts: 1842
    • View Profile
    • My GitHub Page
    • Email
Re: What Is Wrong With This Line Algorithm?
« Reply #1 on: May 17, 2019, 10:20:27 am »
You forgot: line.setPosition(ax, ay);
ZipSavings, script to count rar/7z/zip savings: https://goo.gl/vvBj5M
LuaConsole: https://goo.gl/X4kRUk
FoxRaycaster: https://goo.gl/27nVS8
Small Games - Heart, Routing and Snek: https://goo.gl/15ZGWE https://goo.gl/k5gwWD https://goo.gl/4nKPnT
Botes - a notes app in Pascal: https://goo.gl/bzTqsi

SkeleDotCpp

  • Newbie
  • *
  • Posts: 12
    • View Profile
Re: What Is Wrong With This Line Algorithm?
« Reply #2 on: May 18, 2019, 02:15:08 am »
Oh wow, it worked. I don't know how that passed my potato brain, but thank you for responding!