Listening to navigation keys


/ Published in: ActionScript 3
Save to your folder(s)

Listen to the Navigation keys and save their values in local Booleans


Copy this code and paste it in your HTML
  1. private var goRight:Boolean = false;
  2. private var goLeft:Boolean = false;
  3. private var goDown:Boolean = false;
  4. private var goUp:Boolean = false;
  5.  
  6.  
  7. public function Main()
  8. {
  9. stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
  10. stage.addEventListener(KeyboardEvent.KEY_UP, upHandler);
  11. }
  12.  
  13. private function keyHandler(e:KeyboardEvent):void
  14. {
  15. switch (e.keyCode)
  16. {
  17. case Keyboard.UP:
  18. goUp = true;
  19. break;
  20.  
  21. case Keyboard.DOWN:
  22. goDown = true;
  23. break;
  24.  
  25. case Keyboard.LEFT:
  26. goLeft = true;
  27. break;
  28.  
  29. case Keyboard.RIGHT:
  30. goRight = true;
  31. break;
  32.  
  33. default:
  34. trace(e.keyCode);
  35. break;
  36. }
  37. }
  38.  
  39.  
  40. private function upHandler(e:KeyboardEvent):void
  41. {
  42. switch (e.keyCode)
  43. {
  44. case Keyboard.UP:
  45. goUp = false;
  46. break;
  47.  
  48. case Keyboard.DOWN:
  49. goDown = false;
  50. break;
  51.  
  52. case Keyboard.LEFT:
  53. goLeft = false;
  54. break;
  55.  
  56. case Keyboard.RIGHT:
  57. goRight = false;
  58. break;
  59.  
  60. default:
  61. trace(e.keyCode);
  62. break;
  63. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.