views:

46

answers:

2

Within the container "BubbleContainer" I have multiple "Bubble sprites". Each bubble's graphics object (a circle) is updated on a timer event.

Let's say I have 50 Bubble sprites and each circle's radius should be updated with a mathematical formula. How do I organize this logic?

  1. How do I update all Bubble sprites within the BubbleContainer? (should I call a bubble.update() function or make a temporary reference to the graphics object?)

  2. Where do I put the Math logic? (as static functions?)

+1  A: 

Put as few calls as possible. Static i heard is slower than class methods.

Cristi Băluță
+1  A: 

If I were you I would worry more on how to efficiently do the Math rather than passing the data around because there you loose a big amount of time.

My advice on this would be:

Do all the calculation on the BubbleContainer (or anywhere else, but in one place rather than inside each object)

  • Precalc things like Math.PI/180

  • Precalc 2 arrays/vectors of sine and cosine values.(It's faster to get
    them from an array rather than
    calling Math.sin/Math.cos each time )

  • Pass the result to the Bubble sprite in 1 call ( as Cristi pointed out )

  • Create a function that accepts input parameters , does all the math and returns the answer.

    For each set of input( on each cal of this function ):

    First see if the answer was calculated before, if it was retrieve it from the answer dictionary.

    if not calculate it and add it to the answer dictionary.

    Create an entry in a dictionary that has the input values as the key and the answer as the value. This way you are creating a cache of answers. For complicated,recurring calculations with a relatively small number of input parameters(as in your situation) it's faster to retrieve answer that you already calculated from a dictionary rather than doing the calculation again. If you'll use an array instead of a dictionary I believe it's going to be even faster..

Quick example, not optimized, just to give you an idea:

function multiply(x:int,y:int):int{ 

var retValue:int; 

var key:String=String(x)+String(y);

if (answers[key]){ retValue=answers[key];} 

else{ retValue=x*y;  answers[key]=retValue;} 

return retValue;

}
Oliver
Thanks for taking this holistic approach.Just to clarify:I now add a number of BubbleSprites to a container MovieClip.On a timer event I call the BubbleSprite.update() on each sprite. This function takes the sprite name ("red", "blue" etc.) and looks up a data value in a static data object - i.e. data["red"][3] - to calculate the radius from. This value is sent to a static calculateRadius function which does all the calcualations and returns a radius value to the BubbleSprite. The BubbleSprite scales the circle object based on this new value. Sounds OK?
dani
There are lots of function calls but if the calculations that you do in the static function calculateRadius are complex I guess this is a good option.
Oliver