I’ve thought about setting up a try/except block (like in Python) to prevent the code crunching a NaN when the period = 0.
You could, and there would probably be nothing especially wrong with this, but most Unity code appears to avoid the try/catch exception handling approach.
- Quite often a simple check with an early abort / exit criteria will do instead
- Exception handling in C# brings performance overhead (unrolling the stack, reflection,) that your typical business app couldn’t care less about, but a game wouldn’t even want to waste 1ms on in a frame.
In some cases it might be unavoidable, such as dealing with a 3rd party assembly that regardless of the inputs given, may throw an exception sometimes, and so you need to be prepared for that. Otherwise look for an easy if(…) test that can be used to wrap or divert the condition from occurring instead.
// Update is called once per frame
void Update()
{
try:
if (period == 0) { return; }//protects against stopping movement@ 0
Exception:
period == 0.0001;
//todo prevent period from equaling 0; NaN
float cycles = Time.time / period;
const float tau = Mathf.PI / 2;
float rawSineWave = Mathf.Sin(tau * cycles);
print(rawSineWave);//shows oscillations between 1 and -1 on console
motionFactor = rawSineWave / 1f + .5f;
Vector3 offset = motionFactor * motionVector;
transform.position = startingPosition + offset;
}