Math Optimization: Normalize

I am creating magnets with a positive and negative charge. This script takes the position of the positive and negative magnets and applies the force to a vector. This occurs each frame on many objects, and is fairly heavy. Anyone have any tips on optimizing it?

var vector:Vector2 = transform.position;

var dist1:Vector2 = vector - positivePosition;
var dist2:Vector2 = negativePosition - vector;
var div1:float = dist1.magnitude/10;
var div2:float = dist2.magnitude/10;
dist1.Normalize();
dist2.Normalize();
dist1 /= div1;
dist2 /= div2;
vector += dist1 + dist2;

thank you in advance,
mike

First, let me say those aren’t real complex operations so this might not be as big a deal as you think. But if you are concerned with speed, here’s a faster way of writing it that actually saves two square root operations:

given vector v;
magnitude = |v|

normalized vector = v / |v|
div = |v|/10

final = norm / div =  (v / |v|) / (|v| / 10)
simplified = 10v / |v|^2

Now why is that useful. It happens that the square of the magnitude is cheaper to find than the actual magnitude because we don’t have to take the square root at the end. Its just x^2 + y^2.

Hence:

var dist1:Vector2 = vector - positivePosition;
dist1 = 10 * dist1 / dist1.sqrMagnitude;

And that’s your simplified equation and that might be several times faster than your original equation.

Without unsafe context you can use this implementation of normalizing vector with fast inverse square root:

    //Union used by InvSqrt
    [StructLayout(LayoutKind.Explicit)]
    struct FloatIntUnion
    {
        [FieldOffset(0)]
        public float x;

        [FieldOffset(0)]
        public int i;
    }

    FloatIntUnion union = new FloatIntUnion();

    //Fast inverse Sqrt
    float InvSqrt(float x)
    {
        union.x = x;
        union.i = 0x5f3759df - (union.i >> 1);
        x = union.x;
        x = x * (1.5f - 0.5f * x * x * x);
        return x;
    }


    //Normalize vector using fast inverse Sqrt
    Vector3 FastNormalized(Vector3 src)
    {
        float inversedMagnitude = InvSqrt(src.sqrMagnitude);
        return src * inversedMagnitude;
    }