About Loops and conditionals


(Elias) #1

A small question about loops. If the game updates every frame, loops are bassicaly replaced with conditionals and got no use at all. Is there any special use for them?


(rostok) #2

Are talking about code flow loops like for(...) or while(...) or am I missing sth?


(Jacob Albano) #3

That’s not true at all. If your update() method contains a loop, that loop will run to completion every time update() is called.


(Elias) #4

Yeah, i am about for(…) & while(…). Is it possible to show me an example, cuz i am really comfused about when use them.


(billy2000) #5

In this example ,lets say your game uses a system witch each entity moves square by square.U want to test each frame if E(enemy) see P(player) and nothing is in his way.U can test this by testing the collisions each square until it hits something. Lets say each square is 5 pixels:

var collisionArray:Array = ["player", "otherObj"];
var i:int=5;
while(!isCollided){
    if(collideTypes(collisionArray,x-i,y)){
        isCollided=true;
        doSomething();
    }
  i+=5;
}

Im not sure how efficient is the algorithm but its a example and i hope it helps :smile: Edited it a bit…forgot the i+=5 >.<


(billy2000) #6

In my example this will happend each frame:


(rostok) #7

simpe example. say you have a bomb entity and want to create explosion effect which will create 200 fragments. in your update method you will have a loop like this

for (var i:int=0; i<200; i++) world.add(new Fragment());

this way in one frame update all fragments are created. otherwise it would take 200 frames (about 6.5 seconds @ 30fps) to create them all. moreover they would be out of sync.


(Elias) #8

True! Basically loops perform an action in 1 frame, so you can do stuff faster and more accurate. Thanks all of you for the examples.


(Ultima2876) #9

Loops are also useful for manipulating data in arrays instead of one element at a time. They’re basically vital if you don’t know the length of the array beforehand (eg if you spawn random enemies every 1-3 seconds and want to move them all by looping through the array - you need a loop to do this).

var myArray: Array = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
for(var i: int = 0; i < myArray.length; i++)
{
  myArray[i] += 50;
}