Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is probably due to crossing the 360 degrees / 0 degrees boundary.</p> <p>Using h = heading i.e. the direction the missile is travelling in, and t = the direction from the missile to the target and f=0.1. Now consider the situation where t is 20 degrees clockwise to h. </p> <p>If h = 180 then t = 200 and h(final) = 0.9*180+0.1*200 = 182, so the missile has turned a small amount clockwise as expected.</p> <p>But if h = 350 then t = 370 = 10 (according to the atan formula), so now h(final) = 0.9*350+0.1*10=316 and the missile has turned a large distance in the wrong direction. </p> <p>You need to add a little logic to check for the zero crossing and avoid this problem.</p> <p><strong>Added comment</strong> </p> <p>OK - atan is always a tricky thing, as b = tan(a) is valid for any a in the range (-inf &lt; a &lt; + inf), but a = atan(b) will always provide a b in some range (bmin &lt;= b &lt; bmin + 360), so as a vector rotates around in a circle, at some point there will be a discontinuity in the calculated angle as it rises past bmin + 360 and immediately drops to bmin or as it falls below bmin and suddenly jumps up to bmin + 360. If I am not making myself clear, then just consider what happens when a clock goes past 12:59 pm. It doesn't continue on to 13:00 (except in Europe), but instead drops back to 1:00 am.</p> <p>Blackbear's answer shows the correct idea. My equivalent 'fix' would be to replace your line</p> <pre><code> heading = (1 - f) * oldHeading + f * Math.atan2(atanY, atanX); </code></pre> <p>with something like</p> <pre><code> TheAngle = Math.atan2(atanY, atanX); if Abs(TheAngle-oldheading) &gt; 180 then TheAngle = TheAngle - Sign(TheAngle)*360; heading = (1 - f) * oldHeading + f * TheAngle; </code></pre> <p>where Sign(x) = +1 for x >=0 and -1 for x &lt; 0</p> <p>Note that my code is not quite in C++, Java, or whatever you are using, so you won't be able to do a direct cut-and-paste - but you should be able to translate it into something useful.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload