In Move a Movie Clip with the Arrow Keys, AS2, we showed you how to move an object UP, DOWN, LEFT or RIGHT using the arrow keys. In this tutorial however, we assume that you want to create a more naturally moving object, for example, steering a car (or tank), or moving an object, such as a ball, from a top-down view.

Register Point The first thing we need to do is create the movie clip that we want to move. It is extremely important that when we create the movie clip we center it's registration point. We want our rotation pivot point to be in the center of our object, not in the top-left corner, which is the default.

Next, let's take a look at the script...

var speed = 2;
var rotation = -90*(3.1415/180);
this.onEnterFrame = function(){
        ball_mc._x += speed * Math.cos(rotation);
        ball_mc._y += speed * Math.sin(rotation);
        ball_mc._rotation -= speed;
        rotation -= speed*(3.1415/180);
        ball_mc._rotation += speed;
        rotation += speed*(3.1415/180);

Just like in Move a Movie Clip with the Arrow Keys, AS2, we have a variable named speed that we can use to control how fast our object moves. On the next line we have a variable name rotation that will indicate the angle of our ball. We want our ball to start off with a rotation of -90 degrees (facing upward), however, the sine/cosine functions we will use later require radians, not degrees (A radian is the angle of an arc created by wrapping the radius of a circle around its circumference). No problem, we can convert degrees into radians by simply multiplying the angle by pi/180.

Each time our program enters a frame (at 30 fps) we check to see if the UP, LEFT and RIGHT keys are being pressed. If the LEFT or RIGHT keys are being pressed we alter the balls rotation accordingly, and create a copy in radians on the next line (Note that we could have created two separate speed variables, one for rotation speed and one for moving forward). If the UP key is being pressed we move the ball in the direction of it's current angle. This is done by multiplying our speed variables by the cosine/sine of our ball's current angle and then adding that value to it's x/y position. We also tell the ball animation to play when the UP key is being pressed.

Just for fun you can try adjusting the speed variable, or create two separate variables for speed and rotation speed.