Friday, November 13, 2009

Speed Up an Unchanged Away3d Scene

Have you have ever noticed your Away3d scene eating up the clock cycles even though the scene has not changed? There may be a very good reason for this... well an annoying reason for this might be a more accurate.

Say you are updating an objects orientation on every update:
plane.rotationX = 240;

Because of the in-preciseness of floating point numbers, this object's rotationX might be set to something very close, but not quite the same as the value before, such as 239.99999999999997. Then on the next update you are setting it to 240 again, and because this is ever so slightly different than the last number, Away3d will re-render the whole part of the that scene. This is unnecessary work, and can cause problems in a mixed flash/html site, where the rest of the site will run more slowly when the flash piece is not even moving or being interacted with.

Here is a way to check if you do indeed need to update a object's value:
 function setIfChanged( target, variable:String, value:Number, precision:Number = 0.001 ) {  
// checks if the new value is within a certain precision "distance" from the other
if ((Math.abs(target[variable - value) < Math.abs(precision)) == false)
target[variable] = value;
}
// use the above function to check if it is really a new value
setIfChanged(plane, "rotationX", 240);


If you use this method to check items you are updating on often (like on every Enter Frame), it will only re-render what it needs to, and when it doesn't it will run much faster and not slow down the rest of the site.