How to Set an ActionScript for the Space Bar

The space bar key on your everyday keyboard is often used in Flash video games and Flash elearning applications. The space bar key is the largest key on the computer and is easy for game players and students to locate and use. Flash can be programmed to interact with key presses, such as when the space bar key is pressed, with ActionScript 3.0 code, Flash's programming language. Setting an ActionScript space bar event requires that you know how to use keyboard event listeners. The event listeners instruct the Flash program to take specific actions like displaying a text message.

Things You'll Need

  • Adobe Flash Professional (CS3, CS4 or CS5 versions)
Show More

Instructions

    • 1

      Start the Flash program. Click "New" from the File menu on the main Flash menu bar. Click the file type "Flash File(ActionScript 3.0)" from the New Document dialog box that appears. Click the "OK" button to close the dialog box.

    • 2

      Select the "Actions" option from the Window menu on the main Flash menu bar to open the Actions editor. Position your mouse cursor on the first line of the Actions editor. Click your mouse button and type in the following code to add a keyboard event listener to the stage that will instruct Flash to process the instructions within the "pressedKey" function when a key has been pressed:

      stage.addEventListener (KeyboardEvent.KEY_DOWN, pressedKey)

    • 3

      Type the following code, starting at the next line in the Actions editor, so that the function "pressedKey" will detect if the space bar key has been pressed and then instruct Flash to process the instructions that are within the function "KeyDetector":

      function pressedKey(event: KeyboardEvent):void

      {

      if(event.keyCode == 32) {keyDetector()}

      }

    • 4

      Type the following code, starting at the next line in the Actions editor, to display the message "The space bar key was pressed" after the space bar key has been pressed:

      function keyDetector():void {

      trace("The spacebar key was pressed")

      };

    • 5

      Copy and paste the following code into the Actions editor to run the ActionScript space bar program error free:

      stage.addEventListener (KeyboardEvent.KEY_DOWN, pressedKey)

      function pressedKey(event: KeyboardEvent):void

      {

      if(event.keyCode == 32) {keyDetector()}

      }

      function keyDetector():void {

      trace("The spacebar key was pressed")

      };

    • 6

      Click the "TestMovie" option in the Control menu on the main Flash menu bar to play the ActionScript space bar movie. Position your mouse cursor over the Flash stage and press the space bar key on your keyboard. Verify that the message "The spacebar key was pressed" appears in the Output panel.

Learnify Hub © www.0685.com All Rights Reserved