Game Development Reference

In-Depth Information

A negative angle involves starting at 0° and rotating in the decreasing-heading direction,

but compasses aren't labeled with negative values! To fix this, the line that has the com‐

ment “fix range” is using a ternary operator to say that if the bearing is less than 0, return

the value the compass would read. For example, if the bearing were −10°, then the

compass bearing is −10° + 360° = 350°. If the value is positive, then it just returns the

same value.

To find the final bearing, we simply take the initial bearing going from the end point to

the start point and then reverse it. The code is produced as follows:

float finalBearing (Coordinate2D startPoint, Coordinate2D endPoint){

//Convert location from degrees to radians

float lat1 = (M_PI/180.) * endPoint.lat;

float lon1 = (M_PI/180.) * endPoint.longi;

float lat2 = (M_PI/180.) * startPoint.lat;

float lon2 = (M_PI/180.) * startPoint.longi;

//Calculate deltas

float dLat = lat2 - lat1;

float dLon = lon2 - lon1;

//Calculate bearing in radians

float theta = atan2f( sin(dlon) * cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)

*cos(dlon));

//Convert to compass bearing

float bearing = theta * (180 / M_PI); //radians to degrees

bearing = ( bearing > 0 ? bearing : (360.0 + bearing)); //fix range

bearing = ((bearing + 180) % 360) //reverse heading

return bearing;

}

The difference here is that we have flipped
lat1
,
long1
and
lat2
,
long2
while converting

the locations to radians. Also, before we return the bearing value, we reverse it by adding

180° degrees to it. The modulo operator (
%
) ensures that values over 360° are rolled over

into compass coordinates. For example, if we calculate a bearing of 350° and add 180°

to it, we get 530° degrees. If you start at 0° and go around 530°, you'll end up at 170°.

The modulo operator will result in the bearing being calculated with this correct com‐

pass value.

Rhumb Line

As discussed before, it is sometimes preferable to take a longer path of constant heading,

called a rhumb line, as compared to constantly changing your heading to follow a great

circle path. The rhumb line will be longer than the great circle, and the distance you are

from the great circle route at any moment is called the
cross track error
. To cross the

Atlantic is about 5% longer if you follow a rhumb line. The extreme example of going

from the East Coast of the United States to China is about 30% longer. However, such