Page 1 of 1

Function that returns the direction between two points

Posted: April 25th, 2012, 3:06 am
by KPence
I can't figure out how to code a function that returns the direction (in degrees 0=right 90=up 180=right 270=down) between two points.

Example:

int point_direction(x1,y1,x2,y2);

point_direction(0,0,180,0)=90

I need it so bad

Re: Function that returns the direction between two points

Posted: April 25th, 2012, 4:07 am
by chili
If "0=right 90=up 180=right 270=down", why should "point_direction(0,0,180,0)=90"??

It should be "point_direction(0,0,180,0)=0".

Re: Function that returns the direction between two points

Posted: April 25th, 2012, 5:12 am
by LuX
Not sure if Chili's answer nail'd it, but you could always use tan(alpha)=(y2-y1)/(x2-x1), if I still remember that one correctly.

Re: Function that returns the direction between two points

Posted: April 25th, 2012, 5:41 am
by chili
Yeah, my post wasn't so much an answer as it was just a confirmation because he seems to be contradicting himself in his question there. :|

You are right LuX in that that is the math he will need to use, although he'll have to massage it a bit to get it into C code.

Re: Function that returns the direction between two points

Posted: April 25th, 2012, 9:12 pm
by KPence
Sorry, it was late and I was tired.

I found it btw

int Game::point_direction(int x1, int y1, int x2, int y2)
{
return((int)(atan2((float)y2-(float)y1,(float)x2-(float)x1)*180 / PI));
}

Re: Function that returns the direction between two points

Posted: April 25th, 2012, 9:56 pm
by Dlotan
edit: nvm

Re: Function that returns the direction between two points

Posted: April 26th, 2012, 3:48 am
by chili
You got it KPence, good job. I will just add my two cents here and recommend that you consider using radians instead of degrees when programming. Radians are the units used by the functions in the libraries, so if you insist on working in degrees you will be constantly converting between the two. This will introduce unnecessary calculations into your code degrading the performance of your programs.

I know degrees just feel more familiar and easier to conceptualize, but once you learn to think in radians, it will make a bunch of other math that much easier to understand. The training wheels have to come off sometime bro. Let me put it this way: if you can't get your head around radians, don't even THINK about attempting to learn 3D graphics. ;)

Anyways, here is how I would write your function to return radians in float:

Code: Select all

float Game::point_direction( int x1,int y1,int x2,int y2 )
{
	return atan2( (float)(y2 - y1),(float)(x2 - x1) );
}
And here it is returning degrees in int:

Code: Select all

int Game::point_direction( int x1,int y1,int x2,int y2 )
{
	return (int)(atan2( (float)(y2 - y1),(float)(x2 - x1) ) * 180.0f / PI);
}