Return to Kroll Design home page

Flash Tutorials (with .FLA files included)

« Return

ActionScript 3

mouseX and mouseY properties to track mouse location

When detecting whether a given keyboard key is down or up, you don't have to have an event listener activated in each frame. Instead, just listen for a key being pressed down, and also listen for a key being let go of: the KEY_DOWN and KEY_UP events. For keyboard detection to work properly, the Flash movie must to clicked on to provide focus, hence the Start button. I hide the Start button upon clicking by making it invisible. This is better than using removeChild, because removing that which gave the Flash movie focus undoes the focus, thus defeating the purpose of having the Start button in the first place.

Download the FLA file

var myTextField:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat("Arial",20,0,true);
myTextField.defaultTextFormat = myTextFormat;
myTextField.x = 100;
myTextField.y = 50;
myTextField.width = 200;
myTextField.height = 50;

var myInstructions:TextField = new TextField();
var myTextFormat2:TextFormat = new TextFormat("Arial",12,0,true);
myInstructions.defaultTextFormat = myTextFormat2;
myInstructions.wordWrap = true;
myInstructions.x = 20;
myInstructions.y = 10;
myInstructions.width = 200;
myInstructions.height = 50;
myInstructions.text = "Press and release the space bar on your keyboard";

var myButton_btn:myButton = new myButton();
myButton_btn.x = 70;
myButton_btn.y = 20;

myButton_btn.addEventListener(MouseEvent.CLICK, startBtn);

function startBtn(myEvent:MouseEvent):void
	myButton_btn.visible = false; // removeChild(myButton_btn) undoes the focus that
                                // clicking the button achieved, so making the button
																// invisible works to both hide the button and 
																// preserve focus for keyboard events.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyup);

var spacebarPressed:Boolean = false;

function keydown(myEvent:KeyboardEvent):void
	if (myEvent.keyCode == 32)
		spacebarPressed = true;
		myTextField.text = "spacebar down";

function keyup(myEvent:KeyboardEvent):void
	if (myEvent.keyCode == 32)
		spacebarPressed = false;
		myTextField.text = "spacebar up";

« Return

©2012 Kroll Design    781.910.3694
Last modified: 12/31/1969 7:00 PM