Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If this is a function that gets called often I would stay away from modular division because it is a relatively expensive operation. In your case, the turns can only ever exceed Pi or -Pi by less than one revolution so we can use adding or subtracting Pi from the value to correct for this mistake which is a cheaper option performance wise.</p> <pre><code>//helper function to determine the distance, in radians, between two headings float AngularDist(float heading1, float heading2) //assumes all headings are between -Pi and Pi { if(heading1*heading2&gt;0.0) //this checks if they have the same sign. If so result will be positive { return(abs(heading1-heading2)); } else //If the headings don't have the same sign we need to do some extra math to check whether it is shorter to turn clockwise or counterclockwise to reach other angle { float clockwise=abs(heading1)+abs(heading2); float counterclockwise=2.0*Pi-clockwise; if(clockwise&lt;counterclockwise) return(clockwise); else return(counterclockwise); } } float turnToRequestedHeading(float initialHeading, float requiredHeading, float turnRate) { if((AngularDist(initialHeading,requiredHeading)/turnRate&lt;1.0) //if the turn is too small return required { return(requiredHeading) } else { float positiveTurn=initialHeading+turnRate //need to check if variable is greater than Pi if(positiveTurn&gt;Pi) positiveTurn-=Pi; float negativeTurn=initialHeading-turnRate //need to check if we variable is less than -Pi if(negativeTurn&lt;-Pi) negativeTurn+=Pi; if(AngularDist(negativeTurn,requiredHeading)&lt;AngularDist(positiveTurn,requiredHeading)) return(negativeTurn); else return(positiveTurn); } } </code></pre> <p>EDIT Saw that my original code to check if the new heading was less than one turn rate away incorrectly used absolute value and corrected it. EDIT 2: commenter is right that the case for handling wrapping from a positive to negative number was incorrect. Fixed it by adding a helper function that just calculates distance. I imagine that this will be inlined by the compiler, but it might be worth checking the disassembly to make sure that it is.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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