For Each problem

This forum is currently in read-only mode.
  • Hi,

    I have 3 weapons and 3 enemies.

    -For Each EnemyWeapon ordered by EnemyWeapon.UID Ascending

    --For Each BadMan ordered by BadMan.UID Ascending

    Do -> EnemyWeapon: Set position to BadMan.ImagePointX("RightHand"), BadMan.ImagePointY("RightHand")

    Ok, nice.

    But all 3 weapons sets the position to the last BadMan in the list of UIDs instead of setting the position to all the 3 enemies.

    Why?

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • that's a nested loop:

    for each weapon do: for each enemy do: set weapon to enemy

    result is:

    -For Each EnemyWeapon ordered by EnemyWeapon.UID Ascending

    --For Each BadMan ordered by BadMan.

    -choose EnemyWeapon 1

    --choose BadMan 1

    ---set EnemyWeapon 1 to BadMan 1

    --choose BadMan 2

    ---set EnemyWeapon 1 to BadMan 2

    --choose BadMan 3

    ---set EnemyWeapon 1 to BadMan 3

    -choose EnemyWeapon 2

    --choose BadMan 1

    ---set EnemyWeapon 2 to BadMan 1

    --choose BadMan 2

    ---set EnemyWeapon 2 to BadMan 2

    --choose BadMan 3

    ---set EnemyWeapon 2 to BadMan 3

    etc etc.

    As you can see, at the end you'll assign every EnemyWeapon to the last BadMan.

    You probably should use something other than a nested loop. Look into containers (http://sourceforge.net/apps/mediawiki/construct/index.php?title=Containers), you could set BadMan and EnemyWeapon in a container and you'd be able to do:

    -EnemyWeapon: Set position to BadMan.ImagePointX("RightHand"), BadMan.ImagePointY("RightHand")

    without even having to specify ordering.

  • The events look OK. Posting a .cap demonstrating the problem might help.

    If you're trying to pair a weapon to an enemy, containers can probably do a much better job of that. Nested for-each loops can be slow with a lot of objects. (eg. 200 of both kinds of objects = 40,000 iterations = about 3 million iterations per second!)

  • Yeah thanks I didn't know what containers was It works perfectly now

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)