Programming Simple Movement


There will come a time when you'll want to control how objects on the Stage are moved around, and you'll want more control than you get with simple tweening. You might be creating a game where the user controls an active object (like a ship), or you might be creating an application where you want to anticipate different movement possibilities. You're going to have to do this using ActionScript. However, before you begin madly coding, you need to understand a little bit about how objects behave in the real world. That means you're going to have to plunge into the world of physics. This shouldn't be a scary thing most of it is just common sense with a dash of math. Where to start? A good place to start is with Isaac Newton's First Law of Motion. Newton's First Law of Motion says, in essence:

Objects in motion tend to stay in motion, and objects at rest tend to stay at rest, unless they are acted upon by an outside force.

This is an easy concept to understand. A ball sitting in the middle of the floor, assuming the floor is level, is going to stay right where it is unless you, or someone else, gives it a shove or kick. After that happens, the ball begins to move in a particular direction. For the moment, don't worry about the forces acting on the ball as it rolls. You'll learn about friction and gravity later.

The same thing applies to an object on the Stage in your Flash movie. If you have a movie clip sitting on the Stage, it's not going to move unless you apply a force in the form of a tween or by using actions.

After you apply a force to an object, it begins to move. This movement can be described in terms of speed or velocity. Although these two terms are similar, there is a significant difference between the two concepts:

  • Speed. Also known as scalar, this is the rate of change in the position of an object.

  • Velocity. Also known as vector, this measures the rate of change in position, but it also includes the direction the object is moving.

For the purposes of this chapter, you'll be dealing with speed. Determining the speed of an object is simple:

 speed = (Original position - current position)/time 

The position is determined by the X and Y coordinates of the object. In a Flash movie, the X,Y grid that you are working with has its 0,0 point in the upper-left corner of the Stage. X values increase to the right and Y values increase toward the bottom of the Stage. (See Figure 19.1). Flash is designed this way because Flash movies are destined for Web sites where you never can be certain of the absolute middle, bottom, or right edges of a user's browser, but where you always know the location of the upper-left corner.

Figure 19.1. The coordinate system in Flash has its point of origin (0,0) in the upper-left corner of the Stage.

graphics/19fig01.gif

After you have speed, it's time to think about acceleration. Acceleration is computed like this:

 acceleration = change in speed/time 

Another way to put that is like this:

 acceleration = (final speed  beginning speed)/time) 

When you think about acceleration, you need to be aware that acceleration includes both speeding up (positive acceleration) and slowing down (negative acceleration).

In Flash 4, you would have had to create a controller movie clip that would continually update the position information for your ball. In Flash 5, you don't have to do that in many cases. In Flash 5, movie clips can be treated as objects , which means you now can attach actions directly to the movie clip itself. You use the onClipEvent() handler to assign actions to a movie clip. The syntax for the onClipEvent() handler is this:

 onClipEvent(movieEvent) {     statement;  } 

The movieEvent arguments that you will be using in this exercise are the load and enterFrame arguments.

Actions enclosed within the onClipEvent(load) handler are executed one timewhen the movie clip loads. Use onClipEvent(load) to initialize variables and properties.

In Flash actions, don't update until you actually exit a frame. In a single frame movie clip, even if the movie clip is continuously looping, you never actually exit the initial frame. Actions in an onClipEvent(enterFrame) are initiated every time the frame is entered. Although it might sound like we're playing semantics, this is a big difference.

As long as the movie clip exists on the timeline, you continuously reenter the initial frame. This eliminates the need for a controller movie clip. This doesn't mean that you'll never use controller movie clips to monitor what is happening on the Stage. It just means that you'll use them for a different reason.

Button Control

To control your Ball movie clip, you need to change the speed of the ball in the x or y direction or in both directions.

You begin by giving the movie clip an instance name and initializing the speed variables to 0 when the movie clip first loads. Use onClipEvent(load) to do this.

In the first exercise, you'll practice controlling an object's speed and acceleration by using a combination of directional buttons in your movie and some ActionScript control.

Exercise 19.1 Controlling Movement with Button Presses

You have a series of options when it comes to controlling the movement of an object on the Stage. The object can move when the following occurs:

  • When a button is pressed

  • When a key is pressed

  • Only while a button or key is pressed

  • Continuously, after a button or key is pressed

    You start by working with constant speed initiated by a button press.

  1. Open movement.fla from the Chapter_19/Assets folder. There are currently two layers : Ball and Buttons.

  2. Select the Ball movie clip on the Stage and open the Instance panel (Window > Panels > Instance). Give the Ball movie clip an instance name of Ball. (See Figure 19.2.)

    Figure 19.2. Assign the Ball movie clip on the Stage an instance name of Ball so that you can control it using ActionScript.

    graphics/19fig02.gif

    You need to give the Ball movie clip in the center of the Stage an instance name so that you can control it using ActionScript.

    Tip

    find it convenient to have my Instance panel docked to my Actions panel when I'm scripting.

  3. When the movie clip first loads, the speed of the ball on the Stage is 0. It's not moving. When you are writing code, it's always a good idea to initialize your variables, so do that first. With the Ball movie clip still selected, launch the Actions panel. Make sure you're working in Expert mode and then enter the following code:

     onClipEvent(load) {     speedX = 0;      speedY = 0;  } 

    Now when the movie clip loads for the first time, your two variables for speed are set to 0. The ball isn't going anywhere .

  4. You want to track the speed of the Ball movie clip continuously. To do that, you need to use another onClipEvent() with the enterFrame argument. In just a

    moment, you'll be adding some code to the directional buttons on the Stage that will let you change the speed of the ball. However, in the meantime, you need to let the ball know how fast it is moving; in other words, you will update its X and Y positions based on the current speed in both the X and Y directions.

    Tip

    Although it might feel a little awkward at first if you're a nonprogrammer, try getting used to using the Expert mode in Flash. It's a lot faster and a lot more flexible that the Normal mode. If you ever find you need to see the parameters for a particular tag, you can quickly toggle back into Normal mode by using Ctrl+N (Windows) or Command+N (Macintosh). Use Ctrl+E (Windows) or Command+E (Macintosh) to return to Expert mode.

  5. You should still have the Actions panel open. Position your cursor after the last curly bracket and add a new line. Then enter the following code:

     onClipEvent(enterFrame) {     this._x += speedX;      this._y += speedY;  } 

    this._x is the x position of this instance of the movie clip and this._y is the y position. += is the addition assignment operator. This operator assigns this._x the current value of this._x plus the value of speedX.

    Tip

    The += operator, also known as addition assignment operator, is used to add the current value of the expression on the left side of the operator to the value of the expression on the right side of the operator. It assigns the resulting value to the expression on the left.The two lines of code below are equivalent:

     this._x += speedX;  this._x = this._x + speedX; 

    Think of it as a shortcutjust a little less code you have to write.

    Note

    What is this ? It's a keyword that references the movie clip to which it's attached. When you need to refer to a property or variable of the movie clip instance that you currently are in, use this.

    These are the only actions you need to assign to the Ball movie clip. At this point, your ActionScript should look like this:

     onClipEvent(load){     speedX = 0;      speedY = 0;  }  onClipEvent(enterFrame){     this._x += speedX;      this._y += speedY;  } 

    Now it's time to add some actions to the buttons on the Stage so that you can tell the ball which direction to move and how fast to move. You begin with the button that increases the speed in the X direction (which makes the ball move right).

  6. Select the button that points to the right and launch the Actions panel. Because this is a button, all the actions must be enclosed in an on(mouseEvent) handler. When this button is released, you want the speed to increase. In the Actions panel, type the following:

     on(release) { } 
  7. To increase the speed of the ball, all you need to do is increment its speed by 1. Use the increment operator (++) to increase the speed of the ball.

  8. Create a new line between the curly brackets of the on(release) action and type the following:

     ++_root.Ball.speedX; 

    Tip

    You don't actually have to use _root in this case to reference the ball because the ball and buttons are on the same timeline. I'm a creature of habit, however.

    Preincrementing the value in this fashion takes the current value of Ball.speedX and adds 1 to it.

Note

What is the difference preincrementing and postincrementing a variable? When you preincrement a variable, you add 1 to the variable and return the new value. When you postincrement a variable, you add 1 to it, but not until after you return the value.

 x = 1;  y = ++x; 

After the second line of code has executed, both x and y are equal to 2.

 x = 1;  y = x++ 

After the second line of code has executed, x=2 and y=1.The value of x wasn't incremented until after the current value of x was assigned to y.


Your code for this button, as illustrated in Figure 19.3, should look like this:

 on(release){     ++_root.Ball.speedX;  } 

Notice that this is going to increase the current speed in the X direction of the ball every time you press and release the button. That means you're adding acceleration into the equation as well.

Figure 19.3. Select the button that points to the right and add the code necessary to move the ball from left to right across the screen.

graphics/19fig03.gif

  1. Test your movie. Every time you press and release the button that points to the right, the ball should pick up a little more speed until eventually it exits the movie.

  2. For the button that decreases the speed in the X direction (which makes the ball go left), you use the same code, except that you change the increment ( ++ ) to a decrement ( - ). Select the button that points to the left and add the following code in the Actions panel:

     on(release){     --_root.Ball.speedX;  } 
  3. Test your movie. Notice that if you press the right button a couple of times to get the ball moving and then press the left button once, the ball doesn't reverse direction; it decreases its acceleration.

  4. The code for changing speed in the Y direction will mirror the code that you just wrote. Remember that you'll need to change speedX to speedY. You'll decrement ( - ) the value for the Up button and increment ( ++ ) the value for the Down button.

  5. Select the button that points up and add the following code in the Actions panel:

     on(release){     --_root.Ball.speedY;  } 
  6. Select the button that points down and add the following code in the Actions panel:

     on(release){     ++_root.Ball.speedY;  } 
  7. That's it. Save and test your movie.

If you want the ball to snap back onto the Stage after it escapes off of an edge, just set up the center button actions to set the speed in both directions to zero and the X and Y positions to a spot within the bounds of your movie.

If you're building a game, you might decide that you want to use the arrow keys instead of buttons to control your ball. That requires a few changes to your code.

Key Press Control

If you would prefer to control the ball by using the arrow keys rather than the buttons, you need to make a few changes to the code in your existing movie.

In the previous exercise, the actions that caused the ball to move were in the four directional buttons. You need to transfer that functionality to the Up, Down, Left, and Right Arrow keys on your keyboard. This time, all your actions will be attached to your movie clip; you won't need the buttons at all.

The onClipEvent(load) will be exactly the same as it was in the previous exercise.

 onClipEvent (load) {     speedX = 0;      speedY = 0;  } 

The onClipEvent(enterFrame) is where all the action takes place. Instead of capturing mouseEvents, you'll be capturing key presses. You do this using the Key object. The Key object is a top-level object. That means you don't actually have to create an instance of the object before you can use it.

What you're interested in is whether a key is being pressed. You'll use the Key.isDown(keycode) method, where the keycode argument is the key code value assigned to a specific key. In this case the key code values will be UP, DOWN, RIGHT, and LEFT. The method returns a value of true if the key specified in keycode is pressed.

In the last exercise, the ball started moving and kept on going after you released the button. This time, because you're testing for Key.isDown(), you'll have to add a little additional code to keep the ball on the move when you release the arrow key.

Exercise 19.2 Controlling Movement with the Arrow Keys

You start by setting up the actions for the Right Arrow key. If the Right Arrow key is being pressed, you want to move the ball on the Stage.

  1. You still should be working in movement.fla or you can open keymove.fla in the Chapter_19/Assets folder on the CD.

  2. Delete the Buttons layer.

  3. Select the Ball movie clip and launch the Actions panel. Delete the actions inside the old onClipEvent(enterFrame) handler that you used when you set up the buttons on the Stage. Enter the following code between the asterisks (see Figure 19.4):

     onClipEvent (load) {     speedX = 0;      speedY = 0;  }  onClipEvent (enterFrame) { //********************************      if (Key.isDown(Key.RIGHT)) {         ++speedX;      }  //********************************  } 

    If the Right Arrow key is pressed, you increment the current speed in the X direction and you update the X position of the ball on the Stage. However, that's not quite enough. You also need to tell the ball what to do when the Right Arrow key is not being pressed. You need to add an else to your if statement.

  4. To keep your ball moving, add the following code after the curly brace that closes the if statement:

     this._x += speedX; 
    Figure 19.4. This time, you add all your actions to control the movement of the ball to the ball itself.

    graphics/19fig04.gif

    This little snippet of code keeps the ball moving at a constant speed when the arrow key is not being pressed. Otherwise, the ball would stop when you stopped pressing the arrow key. Your code should now look like this:

     onClipEvent (load) {     speedX = 0;      speedY = 0;  }  onClipEvent (enterFrame) {     if (Key.isDown(Key.RIGHT)) {         ++speedX;      }      this._x += speedX;  } 
  5. Test your movie to make sure you've entered the code correctly.

    Tip

    It's always a good idea to check your syntax before you test your movie. When you're in the Actions panel, you can use Control+T (Windows) or Command+T (Macintosh).

  6. Now you should be able to complete the rest of the if/else statements for the other three arrow keys. If you're not sure what you should do, check Listing 19.1. Remember that cut and paste is your friend.

    Listing 19.1 The Completed ActionScript for Moving the Ball Around the Stage Using Key Presses
     onClipEvent (load) {     speedX = 0;      speedY = 0;  }  onClipEvent (enterFrame) {     if (Key.isDown(Key.RIGHT)) {         ++speedX;      }      if (Key.isDown(Key.LEFT)) {         --speedX;      }      if (Key.isDown(Key.UP)) {         --speedY;      }      if (Key.isDown(Key.DOWN)) {         ++speedY;      }      this._x += speedX;      this._y += speedY;  } 
  7. Test your movie. Notice that the acceleration increases continuously if you hold down a key.

You know how to use button presses and key presses to move objects. Next take a look at how you can pick up an object and throw it.



Inside Flash
Inside Flash MX (2nd Edition) (Inside (New Riders))
ISBN: 0735712549
EAN: 2147483647
Year: 2005
Pages: 257
Authors: Jody Keating

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net