Say you need to calculate the velocity of a gameobject in motion and you can't or dont want to put a rigidbody on it. Whats the easiest way to do it?
Here's how I calculate velocity using co-routines:
void Start ()
{
StartCoroutine( CalcVelocity() );
}
IEnumerator CalcVelocity()
{
while( Application.isPlaying )
{
// Position at frame start
prevPos = transform.position;
// Wait till it the end of the frame
yield return new WaitForEndOfFrame();
// Calculate velocity: Velocity = DeltaPosition / DeltaTime
currVel = (prevPos - transform.position) / Time.deltaTime;
Debug.Log( currVel );
}
}
To test it out, attach it to a moving game object. Very simple and straightforward, but can be used in a lot of places.