A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: help with a for loop please!

  1. #1
    Member
    Join Date
    Feb 2009
    Posts
    49

    help with a for loop please!

    Hey guys, kinda a nooby question with a for loop....
    I have 4 objects that I all want to have their own velocities.

    I have a bunch of variables (each one has a different value):

    PHP Code:
    public var vx1:Number;
    public var 
    vx2:Number;
    public var 
    vx3:Number;
    public var 
    vx4:Number
    Rather than having a function for each object to say:

    PHP Code:
    function1 this.vx1}
    function2 this.vx2}
    function3 this.vx3}
    function4 this.vx4
    I'd like to have a for loop to have my objects x position to += vx(1 through 4):

    PHP Code:
    for (var i:Number=0i<5i++) 
        {
            
    this.+= (vx+[i]);
            } 
    So I tried the above with a combination of " " around different parts of (vx+[i]) but I realized that turning any of it into a string means 'this.x' cannot read it because x has to be a number not a string.

    So how can I make this.x = vx1 then vx2 and so on with a for loop?

    Thanks

  2. #2
    rabid_Delineator AttackRabbit's Avatar
    Join Date
    Dec 2003
    Location
    Orlando, Florida
    Posts
    481
    use array notation

    Code:
    for( var i : Number = 1 ; i < 4 ; i ++ ) {
    	this.x += this["vx" + i];
    };

  3. #3
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    And you should have used an actual array for your vxs to begin with.
    Code:
    var vxs:Array = new Array();
    now you can use the array elements directly in place of your variables. Arrays start at 0 rather than 1.
    Code:
    vxs[0] = 5;
    vxs[1] = 4;
    vxs[2] = 0;
    vxs[3] = -2;
    Code:
    for( var i:int = 0 ; i < 4 ; i++ ) {
    	this.x += vxs[i];
    };

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center