Now let’s try to code everything we’ve seen.
We will use a new Unity Class, called MATHF, which contains, as the word itself says, the mathematical part that we will need.
To have some fun, we will write some formulas ourselves and use MathF just to make testing easier.
This is because: surely to do calculations and more we will almost always use the MathF class, but knowing how to adapt the formula to our purposes is an excellent exercise in mathematical logic.
Don’t panic, everything will be very simple!
Our last scene was this:
What we want now is for the speed to be the same for both sprites, regardless of the distance from the circle.
To put into practice the formulas seen above, we will create 3 different methods: one for the DISTANCE, one for the NORMALIZATION of the Vector, and finally one for the POW.
NOTE : As we have in the previous article, the Distance method already exists, just like the Normal () method and the Pow method (which in fact we will use) in the MathF Class.
What we’re going to do is simply apply formulas to our code, in a very basic way.
Ok, let’s get started!
Let’s start from the end: the Pow method is really very very simple, and here in fact we will use the MathF class
Reference to MathF
In this case we will use the static Pow method
Of course we could write
return value * value;
MathF.Pow is an obviously more complete, it allows us to pass two values: the number we want to raise, and the power.
Mathf.Pow (value, 2);
so our value will be raised to the second.
Mathf.Pow (value, 3);
while thus it will be raised to the third.
Simple but very very useful.
We will continue in the next article, if you want as an exercise you can try to create the various methods yourself using the right formulas!