Reputation: 664
I know there's a lot of questions on this but I'm really having troubles getting this to work.
I only have in the first frame this code:
var game = new Game(this);
In the game class I have a lot of stuff
package {
import flash.display.*;
import flash.ui.*;
import flash.events.*;
public class Game extends MovieClip {
public function Game(esc) {
var camp = new Camp(); //camp és l'escenari, el conjunt de celles
var player = new Player();
esc.addEventListener(KeyboardEvent.KEY_UP, controlTeclat);
camp.mostraInterficie(esc);
player.situaPlayer(esc);
}
public function controlTeclat(ev){
switch(ev.keyCode){
/*case 37: player.moveLeft();break;
case 38: player.moveUp();break;
case 39: player.moveRight();break;
case 40: player.moveDown();break;
case 32: player.dropBomb();break;*/
}
trace ("hi");
}
}
}
The problem is that the controlaTeclat() function's never called, the trace is no printed. No error displayed, dough.
Upvotes: 1
Views: 190
Reputation: 18757
if (esc.stage) esc.stage.addEventListener(KeyboardEvent.KEY_UP, controlTeclat);
else trace("Stage is inaccessible!");
The best practice is allocating your keyboard listeners to stage, so that they will always react to keyboard events. "esc" is your Document class seemingly, but it's not the stage, so we use "stage" property of "esc" to get access there.
Upvotes: 0
Reputation: 1197
You could just add the keyboard listener to the stage itself. You can also set the focus with 'stage.focus' so it will receive events without having to click on the stage first.
stage.addEventListener( KeyboardEvent.KEY_UP, keyupHandler );
//if you want to, you can set focus like this:
stage.focus = stage; //or some other object
private function keyupHandler(e:KeyboardEvent):void
{
trace("keyupHandler()");
}
Upvotes: 0
Reputation: 19748
Without more code it's hard to say exactly what's going wrong here, however if the esc object doesn't have focus (hasn't been clicked by the mouse) then keyboard events won't propagate through it and so the handler won't fire.
Upvotes: 1
Reputation: 123
The mc will need to be on the displayList to receive keyboard events.
var game = new Game(this);
addChild( game );
Upvotes: 1