Posted By

bshantz on 10/02/10


Tagged

keyboard as3


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

bobbym245
heathbo
donaldleegraham
tspitzr
natiboy
tombarc
onemanstudio
dug
kojok


AS3 Keyboard Arrows Control


 / Published in: ActionScript 3
 

This is the basic setup for keyboard functionality I have used in some form in basically any game I've created with player movement. Useful as a starting point for character controls.

  1. package {
  2.  
  3. import flash.display.MovieClip;
  4. import flash.events.Event;
  5. import flash.events.KeyboardEvent;
  6.  
  7.  
  8. public class KeyboardController extends MovieClip {
  9. private var upArrow:Boolean;
  10. private var downArrow:Boolean;
  11. private var leftArrow:Boolean;
  12. private var rightArrow:Boolean;
  13.  
  14. public function KeyboardController() {
  15.  
  16. /* Wait for object to be added to stage so we can reference it */
  17. this.addEventListener(Event.ADDED_TO_STAGE, init);
  18. }
  19.  
  20. private function init(event:Event):void
  21. {
  22. /* Add keyboard listeners to the stage */
  23. stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
  24. stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
  25. /* Run update every frame */
  26. addEventListener(Event.ENTER_FRAME, update);
  27. }
  28.  
  29. private function update(event:Event):void
  30. {
  31. /* Check each arrow and do something if they are pressed */
  32. if(leftArrow) {
  33. trace('left Arrow Pressed');
  34. }
  35. if(rightArrow) {
  36. trace('right Arrow Pressed');
  37. }
  38. if(upArrow) {
  39. trace('up Arrow Pressed');
  40. }
  41. if(downArrow) {
  42. trace('down Arrow Pressed');
  43. }
  44. }
  45.  
  46. private function handleSpacebar():void
  47. {
  48. /* Do spacebar action */
  49. trace("Spacebar hit");
  50. }
  51.  
  52. private function keyPressed(event:KeyboardEvent):void
  53. {
  54. /* Use a switch to determine which key was pressed */
  55. var code:uint = event.keyCode;
  56. switch(code)
  57. {
  58. case 37:
  59. leftArrow = true;
  60. break;
  61. case 38:
  62. upArrow = true;
  63. break;
  64. case 39:
  65. rightArrow = true;
  66. break;
  67. case 40:
  68. downArrow = true;
  69. break;
  70. case 32:
  71. handleSpacebar();
  72. break;
  73. }
  74. }
  75.  
  76. private function keyReleased(event:KeyboardEvent):void
  77. {
  78. /* Use a switch to determine which key was released */
  79. var code:uint = event.keyCode;
  80. switch(code)
  81. {
  82. case 37:
  83. leftArrow = false;
  84. break;
  85. case 38:
  86. upArrow = false;
  87. break;
  88. case 39:
  89. rightArrow = false;
  90. break;
  91. case 40:
  92. downArrow = false;
  93. break;
  94. }
  95. }
  96. }
  97. }

Report this snippet  

You need to login to post a comment.