Mathematical problem.

I’m having a problem with my Distance / maxDrain calculation.

My maxDrain is set to 10.

And the distance i calculate with

var Distance = Vector3.Distance(player.position, transform.position);

And my drainable sanity is set to 100. Why does it drain it from 100 to 0 under a second?

sanity -= (Distance / maxDrain);

sanity -= (Distance / maxDrain);

^ will drain that amount every frame.

Try:

sanity -= (Distance / maxDrain) * Time.deltaTime;

I’m assuming this is called in Update()?

If so, there are two pitfalls with that:

  • Update() is called very often (usually 30-60 times per second)
  • It’s difficult to predict how much time will pass between Update() calls

Let’s assume you have maxDrain expressed in units-per-second (ie: drain up to 10 sanity per second). In that case, you want to multiply your drain rate by the number of seconds since the last Update() call, which in Unity is Time.deltaTime:

sanity -= (Distance / maxDrain) * Time.deltaTime;

This will give you a very small number (assuming 50 frames per second, Time.deltaTime will be about 0.02), but if you’re careful to express all of your math in units-per-second, applying these small changes every frame can actually produce very smooth results.

I’m assuming the rest of your math is fine, but I may be able to help if you’re having any problems with that.