I am currently developing a new 2D mobile game with the Unity game engine. There were no problem until I needed mathematics. Indeed, I need to calcul thespeed of rotation of a circle to make 180° in a given distance and speed. I will show you how you can calculate this speed in C# and adding it to you animation.
Here are the informations we know for having the result you can see on the left
- Distance : d = 5m
- Speed of the circle : v = 2m/s
- Rotation from start to end : 180°
- Radius of the circle : 0.5m
On the paper
First, you need to know the time to travel the distance : t = d/v = 5/2 = 2.5s
Then, you need to make 180° in 2.5 second. That equal to pi/radian=180°
The speed of the rotation is : pi/time = pi/2.5 rad/sec = 1.256
To convert that speed of rotation (1.256) in m/s you need to calculate:
speed rotation * radius = 1.256 * 0.5 = 0.0628m/s
That’s it for the « paper » version.
In C#
I will assume that you already set an animator with a rotation animation for your gameobject.
- In your animator controller, add a new parameter as float called « rotationSpeed ».
- In your animation settings, check « parameters » under « Speed > multiplier » and select rotationSpeed.
Don’t forget to uncheck « Loop time » for your rotation animation.
float time;
float playerSpeed = 2f;
flaot distance = 5f;
float radius = 0.5
/*** FUNCTION UPDATE ***/
// Time needed to travel the distance:
time = distance / playerSpeed;
// Get the rotation speed, convert it in m/s and set the value to the rotationSpeed. It will speed the animation
animator.SetFloat ("rotationSpeed", (Mathf.PI / time) * radius);
// Play the rotation animation
animator.Play ("rotationToLeft");
I hope it will help many of you 🙂