Switch
EXAMPLE 1 (first way)
var a: Number = 3;
if(a==1)
{
trace("one");
}
else if (a==2)
trace("two");
else if (a==3)
trace("three");
else
{
trace("other");
}
EXAMPLE 2 (better way)
var a: Number = 3;
switch(a){
case 1:
trace("one");
break;
case 2:
trace("two");
break;
case 3:
trace("three");
break;
default:
trace("other");
break;
}
The above traces ‘3’
The following traces ‘1’ and 2’:
EXAMPLE 3
switch (a) {
case 1 :
trace("one");
case 2 :
trace("two");
break;
}
Maybe you can understand switch from the examples. Even if you can, I will tell you how I see it.
Say you want something to happen if an actor is something, or somewhere. If the actor is five feet away from the wall you want him to fall, if he is ten feet away from the wall you want him to hop, if he is 20 feet from the wall you want him to run etc. An if statement (remember they work like functions) for this may look like the following example.
var duhMan:Object=new Object();
if(duhMan==<=20)
{run();}
else if(duhMan==<=10)
{hop();}
else if(duhMan==<=5)
{fall();}
else
{stand();}
This seems rather short, but in more complex situations it may start scrambling your brain. Another way you could do this is to switch the actor’s instructions by saying “in this case” followed by the circumstances, which is followed by the instructions:
var duhMan:Object=new Object();
switch(duhMan){
case duhMan==<=20:
{run();}
break;
case duhMan==<=10:
{hop();}
break;
case duhMan==<=5:
{fall();}
break;
default:
{stand();}
break;
In simple terms, this is like saying:
In the case that duhMan is less than or equal to 20, run. In the case that duhMan is less than or equal to 10, hop. In the case that duhMan is less than or equal to 5, fall. By default duhMan is standing.
The ‘break’ is like the period at the end of the sentence.
Of course, run, hop, fall, and stand would be functions we could create.
function run():void{duhMan.x+=20;}
function hop():void{duhMan.x+=10;duhMan.y-=5;}
function fall():void{duhMan.rotation=180;}
function stand():void{duMan.rotation=90;duhMan.x+=0;}