Keyboard Events

It is not a good idea to have the same code in two different places.
When either the button is clicked or the key is pressed we will call the same function
In this exercise we will allow the user to either use buttons or the keyboard to move the movie clip.
Get Adobe Flash player
Add buttons to a layer above the blob and name them btnLeft, btnUp, btnRight, btnDown and btnRotate.
(These buttons are in the buttons library under classic buttons, key buttons.)
stage.addEventListener(KeyboardEvent.KEY_DOWN, doKeyDown);
btnLeft.addEventListener(MouseEvent.CLICK, doButtonClick);
btnRight.addEventListener(MouseEvent.CLICK, doButtonClick);
btnUp.addEventListener(MouseEvent.CLICK, doButtonClick);
btnDown.addEventListener(MouseEvent.CLICK, doButtonClick);
btnRotate.addEventListener(MouseEvent.CLICK, doButtonClick);
var amount:int=1;
function doButtonClick(e:MouseEvent):void {
	if(e.shiftKey) amount=5;
	else amount=1;
	switch(e.target) {
		case btnDown: moveDown(); break;
		case btnUp: moveUp(); break;
		case btnLeft: moveLeft(); break;
		case btnRight: moveRight(); break;
		case btnRotate: rotateBlob(); break;
	} //switch
} //doButtonClick

function doKeyDown(e:KeyboardEvent):void {
 var amount:int=1; //amount to move by
  if(e.shiftKey) amount=5; //make it 5 if shift is down 
  switch(e.keyCode) {
	 case Keyboard.DOWN: moveDown(); break; //down arrow
	 case Keyboard.UP: moveUp(); break; //up arrow
	 case Keyboard.LEFT: moveLeft(); break; //left arrow 
	 case Keyboard.RIGHT: moveRight(); break; //right arrow
	 case Keyboard.R:  rotateBlob(); break;
  } //switch
} //doKeyDown

function moveDown(): void {   //move down if not at bottom
    if(blob.y<stage.stageHeight-blob.height) 
	    blob.y+=amount;
} //goDown
function moveUp(): void {   //move down if not at bottom
    if(blob.y>0) 
	    blob.y-=amount;
} //goUp
function moveLeft(): void {   //move down if not at bottom
    if(blob.x>0) 
	    blob.x-=amount;
} //goDown
function moveRight(): void {   //move right if not off right
    if(blob.x<stage.stageWidth) 
	    blob.x+=amount;
} //moveRight
function rotateBlob(): void {   //move right if not off right
    if(amount==5)  amount=-1;
	blob.rotation+=amount;
} //moveRight
Download the FLA file

NEXT: Drag and Drop