How do I avoid division in this example

I’m trying to calculate the velocity of an object to apply it as a rotation.

I have distanceTravelled / Time.time, but I want to avoid divide by zero errors if the distance traveled is 0. I know that doing divisions every frame is a performance issue and was wondering if there is anyway to perform this calculation with a multiplication.

Do something like this in your Update loop-

Vector3 previousPosition = Vector3.zero;

void Start()
{
    previousPosition = transform.position;
}
void Update()
{
    Vector3 currentVelocity = (transform.position - previousPosition) / Time.deltaTime;
    float currentSpeed = currentVelocity.magnitude;
    // reset the previousPosition now
    previousPosition = transform.position;
}

This way, you always have a momentary view of the object’s velocity.

Please note that from a performance optimisation point of view, the amount of time you will spend on this division operation is tiny compared with improvements you could get with other things (like graphics). If you are going to be speeding up your code, start with the things that are being done hundreds of times per frame- this calculation will be happening only 60 times every second (if you’re lucky), which is hardly any load on the CPU at all.

Also, these days division is no more difficult than multiplication- CPUs have inbuilt processors for both. Honestly, from a performance perspective, there are other, much more important, things you should be worrying about first.

Well, first of all a division will always stay a division. All you can do is calculate a factor out of the divisor but that calculation is also a division. c = a / b can be expressed as c = a * f where f = 1 / b. The only situations where you would do something like that is when the divisor is a constant so it can be precalculated, or you need to divide a lot numbers by the same divisor.

In all those cases you have to zero-check your divisor. Note: A division by zero only happens when the divisor is zero not the dividend. If the dividend(a) is zero the quotient(c) will also be zero as long as the divisor(b) is not zero.

Your divisor is Time.time. The only case where it can be zero is at start of your game. You can either make sure that your code is not executed in the first frame, or check Time.time before your division.

In the end it doesn’t really matter. A division is not that much slower than a multiplication. There are hundreds of other issues in Unity which can really slow you down, but not simple math.

http://stackoverflow.com/questions/226465/should-i-use-multiplication-or-division