Here is an example of what we will be making.
Arrow Keys to move, Internet Explorer users will need to click on it for it to work.
Open a new Flash document and make a character that you want to use for the tutorial. Make it a movieclip (make sure the registration point is on the left) and give it an instance name of ¡®man¡¯.
Select the frame that the ¡®man¡¯ MC (Movieclip) is on and open the actionscript panel (F9 or Window > Actions) and enter the following:
- onEnterFrame = function () {
- man._x>(Stage.width+6) ? man._x=(0-(man._width-5)) : null;
- man._x+man._width<(-6) ? man._x=(Stage.width+5) : null;
- Key.isDown(Key.LEFT) ? man._x -= 2 : null;
- Key.isDown(Key.RIGHT) ? man._x += 2 : null;
- };
If you hit Ctrl+Enter you should be able to see something like what I had up the top.
As always, the first line means ¡®Everytime this frame is entered, run the script between the curly braces¡¯. So this would happen 12 times a second if you movie is running at 12 fps. Mine is running at 36 fps, so it is happening 36 times a second.
The next line might look a bit confusing, but it is actually really simple. It is just an if statement, but in shorthand.
Normal if statement:
if(condition){
//some code;
}else{
//else do this;
}Shorthand:
condition ? //some code : //else do this;So:
if(x == 5){
x¨C;
}else{
x++;
}is the same as
x == 5 ? x¨C : x++;
If there is no else, you just put null after the ¡®:¡¯, or if you are really lazy you can just put 0.
So:
man._x>(Stage.width+6) ? man._x=(0-(man._width-5)) : null;
Means ¡®if the ¡®man¡¯ MC¡¯s _x > the stage width plus 6 (that just makes sure it is completely off the stage), that the mans _x will become -5 minus its width¡¯, so it will be 5 pixels from the left of the stage. As you can see I put null at the end since there is no else needed.
man._x+man._width<(-6) ? man._x=(Stage.width+5) : null;
This is basically the same thing except it checks if the ¡®man¡¯ MC if off the left side of the screen, and if it is it gets placed onto the right side of the screen.
Key.isDown(Key.LEFT) ? man._x -= 2 : null;
This is what makes the MC move left. It checks if the left key is down (Key.isDown(Key.LEFT)), and if it is it decreases the ¡®man¡¯ MC¡¯s _x by 2.
Key.isDown(Key.RIGHT) ? man._x += 2 : null;
This is what makes the MC move right. It checks if the right key is down (Key.isDown(Key.RIGHT)), and if it is it increases the ¡®man¡¯ MC¡¯s _x by 2.
discuss this topic to forum
