For Each problem

New releases and general discussions.

Post » Sun Jul 05, 2009 8:48 pm

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?
B
2
S
1
G
3
Posts: 193
Reputation: 1,486

Post » Sun Jul 05, 2009 9:19 pm

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 ([url:1ku8rmge]http://sourceforge.net/apps/mediawiki/construct/index.php?title=Containers[/url:1ku8rmge]), 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.
B
3
S
2
G
4
Posts: 1,445
Reputation: 4,665

Post » Sun Jul 05, 2009 9:19 pm

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!)
Scirra Founder
B
359
S
214
G
72
Posts: 22,952
Reputation: 178,580

Post » Sun Jul 05, 2009 9:48 pm

Yeah thanks I didn't know what containers was :D It works perfectly now
B
2
S
1
G
3
Posts: 193
Reputation: 1,486


Return to Construct Classic Discussion

Who is online

Users browsing this forum: No registered users and 4 guests