Variables in ActionScript3

In this movie, variables dx and dy have initial values of 0. In the frame event the rockets position is incremented by dx and dy. At start, because dx and dy are both 0, the rocket doesn't move.

When we press the button we assign values to dx and dy. In subsequent frame events, the rocket will move using the new values of dx and dy.

Get Adobe Flash player

The code for this movie is shown below:

var originalX: int=rocket.x; //remember where the rocket started
var originalY: int=rocket.y; //remember where the rocket started
var dx:int=0;
var dy:int=0;

this.addEventListener(Event.ENTER_FRAME,frames);
function frames(e:Event):void {
	//the rocket will not move as long as dx and dy are 0
	rocket.x=rocket.x+dx;
	rocket.y=rocket.y-dy;
} //frames

btnBlastOff.addEventListener(MouseEvent.CLICK, blastOff);
function blastOff(e:MouseEvent):void {
   //put rocket where it  started
   rocket.x=originalX; 
   rocket.y=originalY;
   //after dx and dy are not 0, the rocket will move in the frame event
    dx=2;
	dy=4;
} //blastOff

Every time you press the button, the rocket goes back to its original position and fires. Download this movie.

Experiment: Make separate buttons for re-launching and firing.

NEXT: Select a star to spin