Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an angle and length, how do I calculate the coordinates

Assuming the upper left corner is (0,0) and I'm given an angle of 30 degrees, a starting point of (0,300), a line length of 600, how do I calculate the ending point of the line so that the line is representative of the angle given.

The C pseudo-code is

main() {
  int x,y;

  getEndPoint(30, 600, 0, 300, &x, &y);
  printf("end x=%d, end y=%d", x, y);
}

// input angle can be from 0 - 90 degrees

void getEndPoint(int angle, int len, int start_x, int start_y, int *end_x, int *end_y) 
{

    calculate the endpoint here for angle and length

    *end_x = calculated_end_x;
    *end_y = calculated_end_y;
}
like image 609
amanda Avatar asked Oct 28 '09 16:10

amanda


4 Answers

// edit to add conversion
    #define radian2degree(a) (a * 57.295779513082)
    #define degree2radian(a) (a * 0.017453292519)

        x = start_x + len * cos(angle);
        y = start_y + len * sin(angle);
like image 130
Nick Van Brunt Avatar answered Nov 14 '22 17:11

Nick Van Brunt


You don't say what the angle is measured relative to, or indeed what direction your axes go. These will make a difference.

You first need to convert from degrees to radians (multiply by PI and divide by 180). Then you need to take the sine and the cosine of your angle and multiply these by the length of the line. You now have two numbers for your coordinates, but it depends what directions your axes go and from where you're measuring your angles which of these values is the x coordinate and which is the y, and whether either of them needs to be negated.

like image 35
Weeble Avatar answered Nov 14 '22 17:11

Weeble


// Here is a complete program with the solution in C and command-line parameters
// Compile with the math library: 
//    gcc -Wall -o point_on_circle -lm point_on_circle.c
//
// point_on_circle.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double inline degree2radian(int a) { return (a * 0.017453292519); }

void getEndPoint(double angle, int len, int start_x, 
    int start_y, int *end_x, int *end_y) {
        *end_x = start_x + len * cos(angle);
        *end_y = start_y + len * sin(angle);
} // getEndPoint

int main(int argc, char *argv[]) {
  double angle = atoi(argv[1]);
  int length   = atoi(argv[2]);
  int start_x  = atoi(argv[3]);
  int start_y  = atoi(argv[4]);
  int x, y;

  getEndPoint(degree2radian(angle), length, start_x, start_y, &x, &y);
  printf("end x=%d, end y=%d\n", x, y);

  return 0;
} // main
like image 2
Dave Avatar answered Nov 14 '22 16:11

Dave


math.h has all the trigonometric functions you should need. You may need to give -lm to your linker, depending on what system you're building on (sometimes it's automatic).

like image 1
Carl Norum Avatar answered Nov 14 '22 16:11

Carl Norum