Normally, when making an animation in Flash, you either use a tween or frame-by-frame method to create some motion. However, things are different as far as a game is concerned. That's because in a game players have to be able to control some objects. In this tutorial I'm going to show you how to control objects with Actionscript:
|
Let's see how to create that
i. Create a new Flash document. Set the width to 400 px and the height to 300 px. It's generally advisible to make the width of your canvas greater than the height. :-)
ii. Select the Oval Tool (Ctrl + O) and draw a nice, round circle. If you like, you can draw something
more complex. It's up to you!
|
iii. Select the object and press F8 for the "Convert to a symbol" dialog box to appear. Type whatever in Name, but select Button in Type.
|
iv. Now, select the button you've created and press F9. This time it's the ActionScript window that will appear. Copy and paste the following code in it:
- on(keyPress "<left>"){
- this._x -= 5
- }
- on(keyPress "<right>"){
- this._x += 5
- }
Press Ctrl + Enter to preview the animation. You should now be able to control the famous football player by means of the right and left arrow keys. Obviously, pressing the right arrow key will result his moving right and pressing the left arrow key - left.
Don't worry if you don't understand the above code. Even if you have never dealt with Actionscript, I'm sure you will grasp the code quite easily.
Explanation of the code
- on(keyPress "<left>
" ){
In this first line, we tell the button: " Hey, when I press the left arrow key, you are going to do what is below, after the curly bracket".
- this._x -= 5
"this" refers to the symbol it is on. In this case, it is our button. The dot is used to inform Flash that we're going to refer to a property of the object. Because we want to be able to move our circle left and right, it follows logically that we need to change the x coordinate (move it along the x axis). That's why we use "_x", which refers to the x coordinate of our object. Finally, we subtract 5 from the button's x coordinate by using "-=" sign.
The code responisible for movement in the right direction is very similar to the above one. The only difference is that:
1. In the first line, we have to change "left" to "right".
2. And in the second line, the "-=" sign should be changed to a "+=" sign.
I hope you understood the code and that I didn't make a blunder somewhere in the code. :-) If I did, feel free to tell me where.
Well, I hope this tutorial turned out helpful. If you feel like learning something more, have a look at other interesting tutorials.
Have a good day!


