AS3 example Keyboard control: Difference between revisions
Chris Stout (talk | contribs) m (Changed name of section) |
Chris Stout (talk | contribs) (Added letter-controlled navigation using keyCodes; removed letter-based navigation from todo list) |
||
Line 165: | Line 165: | ||
(still to provide) | (still to provide) | ||
* Adding a jump option triggered by the space letter key. | * Adding a jump option triggered by the space letter key. | ||
=== Using letter keys to control movement (using Keyboard class) === | === Using letter keys to control movement (using Keyboard class) === | ||
Line 200: | Line 199: | ||
If you compare the new code to original code you'll see that the only change was adding a second condition for each direction. Again, The letters need to be capitalized as Flash is case-sensitive. | If you compare the new code to original code you'll see that the only change was adding a second condition for each direction. Again, The letters need to be capitalized as Flash is case-sensitive. | ||
=== Using letter keys to control navigation (using keyCodes) === | |||
As mentioned in the walkthrough, you can use keycodes for keyboard input. Adobe has a [http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html list of all keyboard keys and key code values]. | |||
This method isn't quite as easy to read, but I personally prefer it because it takes less code and doesn't require you to import "flash.ui.Keyboard", which seems to result in a swf that's a few bytes smaller than when using the Keyboard class. I'm including this to demonstrate an alternative to the Keyboard class. [[User:Chris Stout|Chris Stout]] | |||
Here's the code to implement navigation with the letter keys: | |||
<source lang="actionscript"> | |||
private function keyPressedDown(e:KeyboardEvent):void { | |||
var key:uint = e.keyCode; | |||
var step:uint = 5; | |||
/* keyCodes used in this example: | |||
* 37 = Left; 39 = Right; 38 = Up; 40 = Down | |||
* 65 = A; 68 = D; 87 = W; 83 = S | |||
*/ | |||
switch(key) { | |||
case 65: | |||
case 37: | |||
player.x -= step; | |||
break; | |||
case 39: | |||
case 68: | |||
player.x += step; | |||
break; | |||
case 38: | |||
case 87: | |||
player.y -= step; | |||
break; | |||
case 40: | |||
case 83: | |||
player.y += step; | |||
break; | |||
} | |||
} | |||
</source> | |||
== Challenge == | == Challenge == |
Revision as of 05:32, 30 August 2012
<pageby nominor="false" comments="false"/>
Introduction
This example belongs to the AS3 Tutorials Novice and is part of our Actionscript 3 tutorial series.
You will learn how to move a sprite accross the screen with keyboard arrows.
ActionScript Program
package { import flash.display.Sprite; import flash.display.Stage; import flash.events.Event; import flash.events.KeyboardEvent; import flash.ui.Keyboard; public class KeyboardDemo extends Sprite { private var player:Sprite; public function KeyboardDemo() { player = createAvatar(0xFFFF00) // size, color yellow player.x = 200; player.y = 100; addChild(player); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown); } private function keyPressedDown(event:KeyboardEvent):void { var key:uint = event.keyCode; var step:uint = 5 switch (key) { case Keyboard.LEFT : player.x -= step; break; case Keyboard.RIGHT : player.x += step; break; case Keyboard.UP : player.y -= step; break; case Keyboard.DOWN : player.y += step; break; } } private function createAvatar(bgColor:uint):Sprite { var s:Sprite = new Sprite(); s.graphics.beginFill(bgColor); s.graphics.drawCircle(0, 0, 40); s.graphics.endFill(); s.graphics.beginFill(0x000000); s.graphics.drawCircle(-15, -10, 5); s.graphics.drawCircle(+15, -10, 5); s.graphics.endFill(); s.graphics.lineStyle(2, 0x000000, 100); s.graphics.moveTo(-20,15); //this will define the start point of the curve s.graphics.curveTo(0,35, 20,15); //the first two numbers are your control point for the curve //the last two are the end point of the curve return s; } } }
Walkthrough
---
package { import flash.display.Sprite; import flash.display.Stage; import flash.events.Event; import flash.events.KeyboardEvent; import flash.ui.Keyboard; public class KeyboardDemo extends Sprite {
package declaration, import statements, class definition.
---
private var player:Sprite;
we define the sprite that will be moved around the screen. It needs to be declared before the constructor because the variable will be used in different functions.
---
public function KeyboardDemo() { player = createAvatar(0xFFFF00) // size, color yellow player.x = 200; player.y = 100; addChild(player); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown); }
Constructor function. The novelty here is the use of stage. This time, we will listen to events that take place anywhere on the stage rather than a given sprite.
Because we refer to the stage variable, to know what the variable corresponds, we need to import the Stage class. Make sure import flash.display.Stage; is listed among the import statements.
---
private function keyPressedDown(event:KeyboardEvent):void { var key:uint = event.keyCode; var step:uint = 5 switch (key) { case Keyboard.LEFT : player.x -= step; break; case Keyboard.RIGHT : player.x += step; break; case Keyboard.UP : player.y -= step; break; case Keyboard.DOWN : player.y += step; break; } }
This function defines what happens when a keydown event takes place on the stage. Any key down event would trigger that function. This could be pressing on a "a", pressing on a "shift key". Any key pressed will cause this function to execute. We need therefore to write some code that will trigger visible actions only when arrow keys (left, up, right, down) are pressed.
If you have used different computers, at home vs at the lab, desktop vs laptop computer, PC vs Mac, you know that the keyboard can be layed out differently in these different environments. A numeric code is used to provide a unique identifier across environments. Because us, humans, are not very good at remembering a large number of numeric codes, flash kindly provides us with a Keyboard class that has for main function to provide us with easy to read Keyboard information (Keyboard.LEFT, Keyboard.UP, Keyboard.RIGHT, Keyboard.DOWN).
The left, up, right, down variable *must* be written in uppercase because Flash is case sensitive (right, Right, and RIGHT are tree different varibles). They are in uppercase because the convention is to write this way program constants, that is values that don't get to be modified at any point of the program.
We define a step variable for ease of maintenance. For a second, let's imagine we had used player.x -= 5;. If we were to change our mind and change the distance to move by to 40 pixels rather than 5, we would have to change the value in 4 different places. The slightest distraction and we may forget to update all four values, meaning that we will need to compile a first time, identify the error, edit the program file to correct it, re-compile, re-test. It is far less troublesome to create a variable to hold the step value and use that variable when it comes to updating the x and y values of the player.
---
private function createAvatar(bgColor:uint):Sprite { var s:Sprite = new Sprite(); s.graphics.beginFill(bgColor); s.graphics.drawCircle(0, 0, 40); s.graphics.endFill(); s.graphics.beginFill(0x000000); s.graphics.drawCircle(-15, -10, 5); s.graphics.drawCircle(+15, -10, 5); s.graphics.endFill(); s.graphics.lineStyle(2, 0x000000, 100); s.graphics.moveTo(-20,15); //this will define the start point of the curve s.graphics.curveTo(0,35, 20,15); //the first two numbers are your control point for the curve //the last two are the end point of the curve return s; }
We have been playing with graphics a lot, already. This creates a smiley face. A yellow circle in the background, two small black circles for the eyes, a curve for the smile.
---
} }
closing the class definition and then the package declaration. ---
Variants
(still to provide)
- Adding a jump option triggered by the space letter key.
Using letter keys to control movement (using Keyboard class)
There may be several reasons why you would want to allow users to control movement with letters instead of arrow keys. Luckily, using a switch statement such as in this example makes adding alternate controls pretty straight-forward. This first method shows you how using Flash's Keyboard class. I'm using a standard American qwerty keyboard, so I'm choosing w, a, s, and d. You can find a full list of options in the Keyboard class documentation.
Here's the code to add letter key navigation:
private function keyPressedDown(e:KeyboardEvent):void {
var key:uint = e.keyCode;
var step:uint = 5;
switch(key) {
case Keyboard.LEFT:
case Keyboard.A:
player.x -= step;
break;
case Keyboard.RIGHT:
case Keyboard.D:
player.x += step;
break;
case Keyboard.UP:
case Keyboard.W:
player.y -= step;
break;
case Keyboard.DOWN:
case Keyboard.S:
player.y += step;
break;
}
}
If you compare the new code to original code you'll see that the only change was adding a second condition for each direction. Again, The letters need to be capitalized as Flash is case-sensitive.
As mentioned in the walkthrough, you can use keycodes for keyboard input. Adobe has a list of all keyboard keys and key code values.
This method isn't quite as easy to read, but I personally prefer it because it takes less code and doesn't require you to import "flash.ui.Keyboard", which seems to result in a swf that's a few bytes smaller than when using the Keyboard class. I'm including this to demonstrate an alternative to the Keyboard class. Chris Stout
Here's the code to implement navigation with the letter keys:
private function keyPressedDown(e:KeyboardEvent):void {
var key:uint = e.keyCode;
var step:uint = 5;
/* keyCodes used in this example:
* 37 = Left; 39 = Right; 38 = Up; 40 = Down
* 65 = A; 68 = D; 87 = W; 83 = S
*/
switch(key) {
case 65:
case 37:
player.x -= step;
break;
case 39:
case 68:
player.x += step;
break;
case 38:
case 87:
player.y -= step;
break;
case 40:
case 83:
player.y += step;
break;
}
}
Challenge
(incomplete, instructions not clear enough).
Design some dancing mat game type of game. Instructions on the sequence to repeat are given as a sequence of characters "U L R D U U D". There is a starting point and an end point. If the player followed the sequence exactly, he should arrive at the end point.