So you have to get square root from analog input in order to determine how fast should
the character move forward.
But which is better. Having lots of precalculated values where to take comparisons or use Mathf.Sqrt and calculate the exact result or a bit rounded up result.
The values are always between 1 and -1.
I’m just scared of square root because its time taking calculation but these days
computers have a lot of computing power in them for it being little to no problem in
order to solve such a little task.
So, the best way or even better one?
PS: Add more tags and raise the tag limit. Hypotenuse.
You don’t need to calculate the length of input by hand if you pack the values into a Vector2 and use the magnitude value. This still uses sqrt, though.
If you use sqrMagnitude it will avoid using sqrt by giving the length squared. Since there is no value with a greater magnitude of 1 along your axes, you’ll never run into a a squared length greater than 1, since 1 * 1 = 1.
The relationship between numbers and their squares is a curve, like this:
You could probably use this to your advantage, because now you can have a value that gets faster at the edges and slower for sneaking when its closer to the deadzone.
Having the input max out at 1 is also benificial, because now you have a unit value. If you want your speed to be 20, you just have to multiply the square magnitude by it, which will scale your curve to a range of 0 to 20.
It is highly unlikely that this will be your bottleneck. If you are unsure, just test it. Usually I answer these kinds of questions for myself by pushing things “beyond reason” and see what happens. So drop something like this into into your update:
for (var i = 0; i < 100000; i++)
{
var foo = Mathf.Sqrt(Random.Range(0.1,0.9));
}
On my desktop, 100,000 calculations dropped the the frame rate from 66 to 63, and part of that is the Random.Range() call. May be different on your target platform.
Mathf.Sqrt on a modern CPU is only a few times slower than standard math operations (and you’ll find that add/subtract/multiply/divide are all pretty much the same speed too, so the whole “avoid division” thing goes out the window). In fact I found that the time taken by the square root itself on my CPU isn’t so much slower than the overhead of calling the Sqrt function.