Filed under

optimization

 

AS3 Optimization: Faster than Math.sqrt method!

I got this from Michael James Williams, I’m almost embarassed to mention this but, having any sort of Math.function call, especially Math.sqrt in my case, is extremely hazardous to your application. I simply applied his method. Its a bit of a face palm.

For determining distance, which is heavily used for collision detection, one traditionally finds the differences in x and y, and then squares them using Pythagora’s Theorem. The root value of those squared distances added together gives you the exact distance between two objects. So:

dx:Number = objA.x - objB.x;
dy:Number = objA.y - objB.y;

var dist:Number = Math.sqrt(dx*dx + dy*dy);
if(dist < 40){
//slow, but massive explosion
}

Compared to this:

var dist:Number = dx*dx + dy*dy;

if(dist < 40*40){
//quickly animated, but massive explosion
}

That’s all there is to it. A massive increase in speed was seen immediately, since I had a few of those slow Math.sqrt calls.

Filed under  //   actionscript   as3   as3 optimization   flash   flash optimization   optimization  

Comments [1]