The previous tutorial taught you how to make a ball move around on screen with simple interaction. Now we're going to make the movement a bit more complicated and I am going to show you how you can use variables in ActionScript.
Here's what we're going to try to do. What we want is when the user presses a key, it accelerates the ball in that direction. Therefore, we will not just add to the x and y values, but instead add to the x and y SPEEDS.
Here's what we're going to do in this tutorial:
Here's the plan:
We'll need two variables: "vx" and "vy", which will represent the x and y speeds of the ball.
When the user presses the arrow keys. We will not change the x and y values directly, but instead change vx and vy accordingly.
Then, after all the key press tests, we will tell the ball to move with vx and vy.
Start up your flash file from the previous tutorial, but now use this code in the frame, instead of the old code.
Code:
vx = 0; vy = 0; ball.onEnterFrame = function() { if (Key.isDown(Key.UP)) { vy -= .2; } if (Key.isDown(Key.DOWN)) { vy += .2; } if (Key.isDown(Key.RIGHT)) { vx += .2; } if (Key.isDown(Key.LEFT)) { vx -= .2; } ball._x += vx; ball._y += vy; }
Take a look. First we set vx and vy, our variables, to zero, so the ball is not moving anywhere to start.
Then, same as before, we define the onEnterFrame function for the ball. In that function we do the tests. But inside the tests, instead of increasing or decreasing the ball's x and y, we increase/decrease the speeds (notice that we only change the speed by .2. This is because the speed will go up much too fast if we increase it by a bigger value). After we do the tests, we actually move the ball.
Now, as you press the arrow keys, the ball accelerates, rather than staying at a constant speed. Look at what we have now:
