I tried to make the formulas: x = x * cos (d) - y * sin (d), y = x * sin (d) + y * cos (d)

And since it is necessary to rotate relative to an arbitrary point, then from x and y the distance of this point from the origin of the coordinates is first taken away, and then added. Here is the code (C ++):

void rotate(int &x, int &y, const double &cosVal, const double &sinVal, const int &cx = 0, const int &cy = 0) { const double _x = x - cx; const double _y = y - cy; x = round( _x * cosVal - _y * sinVal); y = round( _x * sinVal + _y * cosVal); x += cx; y += cy; } 

But it turns out this (the point relative to which is spinning - the center of the triangle): The triangle is deformed and goes crazy

(GIF recorded from the moment when the triangle has already begun to deform and "leave" from its center).

  • 2
    The code is most likely correct. Are you sure that the rounding error does not accumulate? Try to save the angle and each time recalculate from the starting position. - pavel

1 answer 1

You work with floating-point math, while using variables of type int ! Naturally, [accumulating] rounding errors give absolutely ridiculous results!

Use double variables for coordinates, and translate them into int only for displaying graphics (and that can be implicitly ...)

 void rotate(int &x, int &y, const double &cosVal, const double &sinVal, const int &cx = 0, const int &cy = 0) 

should turn into

 void rotate(double &x, double &y, double cosVal, double sinVal, double cx = 0.0, double cy = 0.0) 
  • Thanks, I started counting in double and it all worked. - Daniil