Game Development Reference

In-Depth Information

//Calculate deltas

float dLat = lat2 - lat1;

float dLon = lon2 - lon1;

//find delta phi

float deltaPhi = log(tan(lat2/2+(M_PI)/4)/tan(lat1+M_PI/4))

float q=(deltaPhi==0 ? dlat/deltaPhi : cos(lat1); //avoids division by 0

if (abs(dLon) > M_PI){

dLon = (dLon>0 ? −(2*(M_PI-dLon):(2*M_PI+dLon));

}

float D = sqrt(dLat*dLat + q*q*dLon*dLo)* 6371;

float theta = atan2f(dLon, deltaPhi);

//now convert to compass heading

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

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

return bearing;

}

There are a few things worth pointing out. First is that we are using a ternary function

in the line commented by “avoids division by 0” to take care of the case when
delta

Phi
is equal to 0. If it is 0,
q
is set to
cos(lat1)
; if not, then it is set to
dlat/deltaPhi
.

The
if
statement immediately following ensures that if
dLon
is greater than π (180°),

hence putting us on a longer-than-required rhumb line, then we should correct the

value to correspond to the shortest route. This is achieved via the ternary, which ensures

that
dLon
is less than π and nonnegative. Lastly, we convert from a normalized radian

answer to a compass direction.

Now that you have a good idea about how to calculate position and distance in the

geographic coordinate system, you can use the earlier chapters to determine other

quantities like speed and acceleration.