8 Replies Latest reply on Oct 30, 2008 6:28 AM by flash_tips

    for() loop, and functions

    Sketchsta Level 1
      Hi
      I'm having a hard time getting past this little issue. I know its possible, but I've hit a mental blank.

      Heres the scenario:
      I have 14 objects, which I want to move about the screen with a Tween function. Im using a for() loop to call upon each object, but I'm stuck here. I dont know how to call each object from that loop with a function.

        • 1. Re: for() loop, and functions
          Sketchsta Level 1
          I hope that makes sense!!
          • 2. Re: for() loop, and functions
            Level 7
            Sketchsta,

            I would do it like the following sample. Note a few differences.
            First, I moved the sparkF() function outside of the explode() function.
            There's no reason (that I could see) to nest the functions. I also added
            strong typing (why don't people do this?). I also added randTime as a third
            parameter to the sparkF() function. Finally, I changed the fourth parameter
            fo your _x and _y Tween instances: you had 0, but I replaced those with
            who._x and who._y. Why? So that the particles will start from wherever
            they happen to be positioned, instead of always from 0. Let me know if that
            doesn't make sense.

            import mx.transitions.Tween;
            import mx.transitions.easing.Strong;

            function explode():Void {
            var randPos:Number;
            var randTime:Number;
            for (var i:Number = 1; i <= 4; i++) {
            randPos = (Math.random() * 200) + 30;
            randTime = (Math.random() * 4) + 2;
            sparkF(this["s" + i], randPos, randTime);
            }
            };

            function sparkF(who, where, when):Void {
            new Tween(who, "_x", Strong.easeOut, who._x, where, when, true);
            new Tween(who, "_y", Strong.easeOut, who._y, where, when, true);
            new Tween(who, "_alpha", Strong.easeOut, 100, 0, when, true);
            };

            explode();

            As shown, your sparks won't explode in all directions. This may be what
            you want, but then again ... may not. I suggest maybe creating separate
            random positions for _x and _y, and in addition, changing the numbers you're
            using for the randomness, to allow some numbers to be positive and some to
            be negative:

            import mx.transitions.Tween;
            import mx.transitions.easing.Strong;

            function explode():Void {
            var randPos:Number;
            var randTime:Number;
            for (var i:Number = 1; i <= 4; i++) {
            randPosX = (Math.random() * 200) - 100;
            randPosY = (Math.random() * 200) - 100;
            randTime = (Math.random() * 4) + 2;
            sparkF(this["s" + i], randPosX, randPosY, randTime);
            }
            };

            function sparkF(who, whereX, whereY, when):Void {
            new Tween(who, "_x", Strong.easeOut, who._x, who._x + whereX, when, true);
            new Tween(who, "_y", Strong.easeOut, who._y, who._y + whereY, when, true);
            new Tween(who, "_alpha", Strong.easeOut, 100, 0, when, true);
            };

            explode();

            In this revision, note that the fifth parameters to the Tween instances
            (for _x and _y) use more than just the parameter formerly known as "where".
            Now each respectively uses whereX and whereY, but on top of that, applies
            that value to the starting position of the spark:

            who._x + whereX


            David Stiller
            Adobe Community Expert
            Dev blog, http://www.quip.net/blog/
            "Luck is the residue of good design."


            • 3. Re: for() loop, and functions
              Level 7
              Sketchsta,

              Heh, meanwhile ... your whole point for posting was to ask how to
              reference those objects, whose instance names are s1, s2, s3, and so on.
              The solution I used was the array access operator:

              sparkF(this["s" + i], randPos, randTime);

              In other words: this["s" + i]


              David Stiller
              Adobe Community Expert
              Dev blog, http://www.quip.net/blog/
              "Luck is the residue of good design."


              • 4. Re: for() loop, and functions
                Sketchsta Level 1
                OMG!!!
                You know what the problem was? ...you're going to laugh!!
                in my randTime variable I had Math.round..instead of Math.random.. =(

                I cant believe how much headache and time i wasted, when all I had to do was READ MY OWN CODE... =(

                ---Let this be a lesson for everyone--- LOL

                Thanx for your help David, always a genius, and always easy to understand and follow.
                I actually didnt think about the separate X and Y variables. I guess I expected it would generate a new number when called for _x, to _y.

                I do need the particles to start from 0 everytime. this is just for a "cheap thrill" inside a banner, when the Home button is clicked.

                --------------
                I also added strong typing (why don't people do this?).
                -------------
                I used to all the time, but I was told that it's not necessary??
                I haven't done this in a long while, and things have worked fine. What are the benefits of coding this way?
                besides the code hints thing!

                I re-typed the whole code, with your layout..not nesting sparkF function. I nested it in the first place, because it wouldnt read the rand.. variables from the for loop? maybe i missed something simple yet again!!

                -------------
                changing the numbers you're using for the randomness, to allow some numbers to be positive and some to be negative:
                -------------
                I love that... I dont think I would have ever thought of this one.
                knowing me, I probably would have moved the sparks away from 0x0 somewhere in the middle, and work the numbers from there. ...pathetic, I know!!
                this is definitely one for the memory bank. =Þ
                • 5. Re: for() loop, and functions
                  Level 7
                  Sketchsta,

                  > OMG!!!
                  > You know what the problem was? ...you're going to laugh!!
                  > in my randTime variable I had Math.round..instead of Math.random.. =(

                  Heh, I saw that too, but failed to point it out in my follow-up
                  suggestion). Oy. Glad you caught that!

                  > I actually didnt think about the separate X and Y variables.
                  > I guess I expected it would generate a new number when
                  > called for _x, to _y.

                  The way your original code was written, it wouldn't. You were setting
                  the value of randPos once, then passing that as a parameter (just one
                  parameter) to another function. As soon as you set the value of randPos, it
                  only has the value it has. Until you set it again, which happens on the
                  next iteration of the for() loop (after which both your _x and _y properties
                  were already tweened).

                  > I do need the particles to start from 0 everytime. this is just
                  > for a "cheap thrill" inside a banner, when the Home button
                  > is clicked.

                  Cool. Even easier, then.

                  > I used to [strongly type] all the time, but I was told that it's
                  > not necessary??

                  It's not necessary.

                  > I haven't done this in a long while, and things have worked fine.

                  Luck of the draw!

                  > What are the benefits of coding this way?
                  > besides the code hints thing!

                  To my thinking, code hinting is helpful, and reason enough. Another
                  benefit, in AS2, is improved error messages at compile time. If you type a
                  variable as Number (because it's supposed to be a number) but accidentally
                  set it to a string (or some other datatype), the compiler is more likely to
                  let you know that. It's not perfect, but it does help.

                  In AS3, strongly typing has even more benefit, because it helps reduce
                  the RAM overhead of your SWF. That's becasue the AVM2 (ActionScript Virtual
                  Machine 2) in Flash Player 9 and higher is smart enough to only request the
                  memory each strongly typed object needs. Otherwise, as in AS2, each new
                  object instance needs enough memory to handle whatever type it *might* be.

                  > I re-typed the whole code, with your layout..not nesting sparkF
                  > function. I nested it in the first place, because it wouldnt read the
                  > rand.. variables from the for loop?

                  That makes sense, and here's why. The variables are declared inside
                  your explode() function, which means the explode() function is their home.
                  The main timeline can't see those variables, and neither can any other
                  object outside of the function. Scope doesn't work in that direction: only
                  from outside in. Meaning, you could declare a variable in the main timeline
                  and "see" it from inside explode(), but not the other way around. That's
                  why I added the third variable to sparkF().

                  > -------------
                  > changing the numbers you're using for the randomness, to allow
                  > some numbers to
                  > be positive and some to be negative:
                  > -------------
                  > I love that... I dont think I would have ever thought of this one.
                  > knowing me, I probably would have moved the sparks away
                  > from 0x0 somewhere in the middle, and work the numbers from
                  > there. ...pathetic, I know!!

                  Nah, not pathetic. Do what works, right? It's the Flash way (and I
                  mean that with affection for Flash). But it's often even easier to change a
                  few numbers somewhere, than to have to keep moving symbols by trial and
                  error.


                  David Stiller
                  Co-author, The ActionScript 3.0 Quick Reference Guide
                  http://tinyurl.com/2s28a5
                  "Luck is the residue of good design."


                  • 6. Re: for() loop, and functions
                    Sketchsta Level 1
                    >Do what works, right? It's the Flash way (and I
                    >mean that with affection for Flash)

                    LOL. I agree.. with much love for Flash.

                    I havent been using AS3 at all.. =(
                    its too different from what im used to in AS2. almost like learning a new language all together.
                    It's on my "ToDo" list tho. I need to make some little project for AS3 when i have time, and get to know it abit better.
                    and i definately will be using hard coding for AS3.. i'll need all the hints i can get. =)

                    i'll be visiting your blog again for hours on end reading through your knowledge of AS3. =)

                    Thanx for all your time Dave. Much appreciated. =)
                    • 7. Re: for() loop, and functions
                      Sketchsta Level 1
                      I marked your last post as the answer as it has a lot of useful info, which other should read. =)
                      but technically, your second post is the specific answer.

                      If anyone is looking for the answer to my topic....read David's second post!
                      • 8. Re: for() loop, and functions
                        flash_tips
                        this.onEnterFrame = function (obj:Boolean)
                        {
                        if ( this.missile_mc._x < 550 )
                        {
                        this.missile_mc._x += 10 ;
                        }
                        }

                        this script moves the object once only how can we move in loop continuously using loop