# How can I calculate velocity without using Rigidbody?

Hello everyone!

This is a problem I have run into while making my space shooter style game. I have a script that I put onto my "targets" in which I get its rigidbody.velocity. I then use that script on my aiming turrets to create a believable "lead time" effect and actually hit when the turret fires. However, I am running into a problem with my "missiles." In order to get them to fly to the target, more or less, I am using transform.translate. Using that and a speed variable (and time.deltatime), I am able to get my missile to where it needs to go.

Now, I have a rigidbody on the missile for collisions and such, but my script doesn't appear to be getting any information about the speed / direction of the missile. I presume its because I am moving it via a transform translate and not a rigidbody.AddForce, but it really behaves a lot better this way.

Is there a way I can "fake" the speed information I would normally get from rigidbody.velocity on my missile object that is moved by transform.translate?

Simple & crude velocity measure:

You can sample the world position on this frame and store the result from the previous frame. You now have two points of reference. Take into consideration how long the time slice was between the two points to derive the velocity. I think the code would be:

``````var velocity = (current - previous) / Time.deltaTime;

``````

If the leap (current - previous) was big, say 5 units to the right and the time slice was small (1/60), we would be going very fast. 5/(1/60) = 300 units per second.

this works:

``````var previous: Vector3;
var velocity: float;

function Update()
{
velocity = ((transform.position - previous).magnitude) / Time.deltaTime;
previous = transform.position;

print (velocity);

}
``````

Hi I was working on the same thing as this recently, and I managed to get something that works for me, even if the velocity hits zero. I only set this up to work on the Y axis but should be easy easy enough to calculate the other axis too.

var camPos : Transform;

Update ()
{

StartCoroutine(curVelocity(0.1));

}

function curVelocity(waitTime : float)

{

``````     var previous : float;
var current : float;
var velocity : float;
previous = camPos.position.y;
yield WaitForSeconds (waitTime);
current = camPos.position.y;
velocity = current - previous;
if (velocity == 0)
{
velocity = 0.000001;
}
velocity = velocity / waitTime;
if (velocity < 0.0001 && velocity > -0.0001)
{
velocity = 0;
}

print (velocity);
``````

}