Using Keys to Move Object

The movie below lets you use keys to move the blob. Look at the code and try to determine what keys can move and rotate the blob:
Get Adobe Flash player
stage.addEventListener(KeyboardEvent.KEY_DOWN, doKeyDown);
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 40: blob.y+=amount; break; //down arrow
	 case 38: blob.y-=amount; break; //up arrow
	 case 37: blob.x-=amount; break; //left arrow 
	 case 39: blob.x+=amount; break; //right arrow
	 case 82: //letter r
	      if(e.shiftKey)  amount=-1; //if shift is down rotate counter clockwise
		  else amount=1;
	      blob.rotation+=amount; //rotate when r is pressed
	      break;
  } //switch
} //doKeyDown
Notice that we do not need curly braces {} around the statements for the letter r: the break ends the block with case rather than curly braces. Download the FLA file

INDEX, Capturing Keyboard Events, Using Keys to Move Object, Keyboard Constants, Combining Keys and Buttons
Next lesson: Drag and Drop

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Using Keys to Move Object