How to Give Strings Functions in AS3

Giving strings functions in AS3 --- ActionScript 3, the Flash Programming Language --- lets you use text commands in sophisticated Flash War games. In such a game, a user enters a text command in a text box to control specific objects. For example, if the user typed in the string "moveTankLeft", a function would be called that would move the Tank object. In such a system, the AS3 code would have to determine what function the string referenced and then call that specific function.

Things You'll Need

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

Instructions

    • 1

      Name the text strings that will be assigned functions. For this example, use the text strings "MoveTankLeft", "MoveTankRight", "MoveTankForward" and "MoveTankBackward."

    • 2

      Type in the ActionScript 3 editor the code that will test if a specific text string has been entered. Use an AS3 "if then" statement for this. Code the "if then" statement so that a specific function will be called for each different text string.

      If (tank.text = "MoveTankLeft") {tankLeft(); };

      If (tank.text = "MoveTankRight") {tankRight(); };

      If (tank.text = "MoveTankForward") {tankForward(); };

      If (tank.text = "MoveTankBackward") {tankBackward(); };

      The code checks to see if the text entered into the tank TextField matches any of four possible text strings. If a string matches, the associated tank moving function is called, and the tank is either moved to the right, left, forward or backward.

    • 3

      Type in the code for each of the functions called. Code the functions such that the tank will move 10 pixels in either the horizontal or vertical direction every time a specific tank moving function is called.

      function tankLeft():void

      {tankLeft.x = tank.x - 10;

      }

      function tankRight():void

      {tankLeft.x = tank.x + 10;

      }

      function tankForward():void

      {tankLeft.x = tank.y - 10;

      }

      function tankForward():void

      {tankLeft.x = tank.y + 10;

      }

      This code defines four functions. The first function, "tankLeft," is executed when the text message "MoveTankLeft" is typed into the TextField. In that case, the tank is moved 10 pixels to the left. When the tank is commanded to go forward it will move 10 pixels up; Flash has an upside down coordinate system.

Learnify Hub © www.0685.com All Rights Reserved