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.
It is much easier to understand the code now becasue we have used the Keyboard constants instead of the code numbers:

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 Keyboard.DOWN: blob.y+=amount; break; //down arrow
case Keyboard.UP: blob.y-=amount; break; //up arrow
case Keyboard.LEFT: blob.x-=amount; break; //left arrow
case Keyboard.RIGHT: blob.x+=amount; break; //right arrow case Keyboard.R: //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.

 
 

Keyboard Constants