• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Hour 9. Getting Input from the User > Task: Keyboard-Controlled Movie Clip

Task: Keyboard-Controlled Movie Clip

Let's use our knowledge of testing the keys on the keyboard to allow the user to move a movie clip around the screen.

Start with a new movie.

Create a simple movie clip. A simple shape such as a circle will do.

Attach this script to it:

onClipEvent(enterFrame) {
    if (Key.isDown(Key.LEFT)) this._x -= 5;
    if (Key.isDown(Key.RIGHT)) this._x += 5;
    if (Key.isDown(Key.UP)) this._y -= 5;
    if (Key.isDown(Key.DOWN)) this._y += 5;

All that this script does is test each of the four arrow keys and send the movie clip a little in that direction if the key is pressed.

Now replace that script with one that is a little more ready for future use. This script stores the starting location of the movie clip in x and y. It also sets the speed variable to 5.

In Every frame that goes by, it tests the four arrow keys but adjusts the x and y variables instead of directly adjusting the location of the movie clip. It uses speed as its adjustment amount. Then it sets the location to x and y:

onClipEvent(load) {
    x = this._x;
    y = this._y;
    speed = 5;

onClipEvent(enterFrame) {
    if (Key.isDown(Key.LEFT)) {
        x -= speed;
        if (Key.isDown(Key.RIGHT)) {
        x += speed;
        if (Key.isDown(Key.UP)) {
        y -= speed;
        if (Key.isDown(Key.DOWN)) {
        y += speed;

    this._x = x;
    this._y = y;

This longer script has two advantages. First, because we are adjusting variables rather than the real location, we can test the new location before making the move. This will come in handy in games where you don't want the object to be seen outside a certain area. Second, this script makes it easy to adjust the speed since it is in one place only.

Because we use speed instead of repeating the number 5 four times, we have one central place where we can adjust the speed of the movie clip.



Not a subscriber?

Start A Free Trial

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint