3 Functions to move a box with the arrow keys
Open a new Flash document and do exactly like in the tuto Flash Function Made Easy 2 for creating the box movie clip; then change the code in the Action pannel as follows (you can select it and paste it in the Actions pannel):
ActionScript Code Explanations var xBox:Number = 200; var yBox:Number = 200; function locateBox() { Box._x = xBox; Box._y = yBox } function moveBoxWithKeys() { if (Key.isDown(Key.RIGHT)) {xBox = xBox+10; yBox = yBox;} if (Key.isDown(Key.LEFT)) {xBox = xBox-10; yBox = yBox;} if (Key.isDown(Key.UP)) {xBox = xBox; yBox = yBox-10;} if (Key.isDown(Key.DOWN)) {xBox = xBox; yBox = yBox+10;} } this.onEnterFrame = function() { locateBox(); moveBoxWithKeys(); } The first two lines place our box in the center of the stage (400x400). Then there is a function called locateBox(); now, you should be able to say what this function does: it just stores the box x coordinate (Box._x) in the variable xBox and the box y coordinate (Box._y) in the yBox variable. You understand why I called it locateBox! Then follows a (long) function called moveBoxWithKeys ; no need to tell you what it does! This function combines 4 actions(the four if): 1-If the RIGHT key is down, the x coordinate is increased of 10 pixels (the y coordinate stays the same). 2-If the LEFT key is down, the x coordinate is decreased of 10 (the y coordinate stays the same). 3-If the UP key is down, the y coordinate is decreased (don’t forget: the y axis is oriented from Top to Bottom); the x stays the same. 4-If the DOWN key is down, the y coordinate is increased and the x stays the same. Finally, the last function makes work the first two functions (it’s a lazy one!): every time we enter a frame, Flash locates the box with the function locateBox and moves it with the function moveBoxWithKeys.
Clear? Test your movie and see your box follow your key commands! You have made work your first functions in Flash!
