In this movie we have two event listeners. In the frame event we move the ball to the right by adding to ball.x . We make the ball move up by subtracting from ball.y.
It we left it like this, the ball would disappear off the top of the stage. However, we also added an event listener for clicking on the stage. When the user clicks on the stage the ball goes to the position that the user clicked.
stage.addEventListener(MouseEvent.CLICK,getBall);
this.addEventListener(Event.ENTER_FRAME,frames);
function getBall(e:MouseEvent):void {
ball.x=e.stageX;
ball.y=e.stageY;
} //getBall
function frames(e:Event):void {
ball.x=ball.x+1;
ball.y=ball.y-2;
} //frames
We have told Flash to execute a function called frames every time the ENTER_FRAME event occurs. The code in this function moves the ball to thee right by giving a new value toball.x that is one more than its current value. It moves the ball up by subtracting 2 from its current value.
Clicking on the stage calls the function getBall. Every function that is called on a mouse event get a packet of information about that MouseEvent. By convention we have called that packet of information e. One of the properties of e is the location on the stage where the mouse was clicked. That location is in the properties e.stageX and e.stageY. When we say ball.x=e.stageX and ball.y=e.stageY we move the ball to the position that was clicked.
Experiment: Modify the code to change the speed and direction that the ball moves.
Experiment: Add the statement trace(e); to the getBall function:
function getBall(e:MouseEvent):void {
trace(e);
ball.x=e.stageX;
ball.y=e.stageY;
} //getBall
Trace: The trace function lets the programmer look at the value of properties and variables. Here all the properties of the MouseEvent variable, e, are shown:
If you do not see any output when you click, open the output window by typing F2 or select Window, Output from the menu.
Experiment by holding shift and clicking, you should see shift=true in the output window. Try some of the other properties of e to change them.
If your movie doesn't work, open the finished movie and check carefully to find what you did wrong.