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;

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.