I would like to trigger an event each time my rigidbody2D is at a particular value.
The event should only be triggered once for each given value per complete object revolution.
Initial attempts at achieving this have resulted in the following method which checks against an array of values, logging an event and incrementing an index when the value has been passed.
static readonly float[] angles = new float[] { 90f, 180f };
int angleIndex = 0;
void CheckForTrigger()
{
if (rigidbody2D.IsSleeping())
return;
var rotation = Mathf.Abs(rigidbody2D.rotation);
if (rotation % 360f >= angles[angleIndex])
{
Debug.Log("Fire");
angleIndex++;
if (angleIndex== angles.Length)
angleIndex= 0;
}
}
This suffers from a couple of issues:
- Floating point inaccuracy means that values close to 360f will often be missed (e.g. 359f)
- Fire will be logged each frame between the last and first value (i.e. between 180f and 90f)
Does anyone have any advice for approaching this problem and improving the above method?