Given a square (described by x, y, width, height) and an angle (in radians) I need to calculate a vector that originates at the squares centre and terminates at the point th
EDIT: the correct solution for rectangles. It even does not crash if width or height are zeros! Language: C++.
tan(89.99999) thanks to James Fassett for testing my code.
#include
#include
// declare nonstandard signum function
double sign(double x);
//define pi because I forgot where it's declared
double const pi = 3.14159;
//declare non-standard contangent function
double cot(double x);
int main()
{
for (double angle = 0.0 ; angle<2*pi; angle += 0.1){
//angle should be within [0, 2*pi) range
//x and y point to the _middle_ of the rectangle
double x = 0; double y = 0 ;
double width = 1, height = 4;
double base_angle = atan(height/width);
// the angle between rectangle diagonal and Ox axis
double px,py;
// Which side we're on?
bool left = (fabs(angle - pi) < base_angle);
bool right = (angle> 2*pi-base_angle || angle < base_angle);
bool top = (fabs(angle - pi/2) <= fabs(pi/2 - base_angle));
bool bottom = (fabs(angle - 3*pi/2) <= fabs(pi/2 - base_angle));
// The helper values used to adjust sides
int lr = (left?-1:0) + (right?1:0);
int tb = (bottom?-1:0) + (top?1:0);
if (lr) {
// we're on vertical edge of rectangle
px = x+width/2*lr;
py = y+width/2*tan(angle)*lr;
} else {
// we're on the horizontal edge or in the corner
px = x+height/2*cot(angle)*tb;
py = y+height/2*tb;
}
printf(" a = %d deg: x = %lf; y = %lf\n",(int)(angle/pi*180),px,py);
}
return 0;
}
// define nonstandard signum function
double sign(double x)
{
if (x<0) return -1;
if (x>0) return 1;
return 0;
}
//define non-standard contangent function
double cot(double x)
{
return tan(pi/2 - x);
}