¿Cómo puedo escribir un controlador KEY_DOWN en ActionScript 3?
-
13-09-2019 - |
Pregunta
Está bien, he tratado de 8 maneras diferentes de obtener un acontecimiento clave en mi código, y ninguno de ellos parece funcionar. ¿Puede alguien por favor dígame cómo puedo mover esta bola cuando pulso turno? Gracias de antemano
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
styleName = "plain"
xmlns="cyanprime.*"
layout="absolute"
width="600"
height="400"
frameRate="100"
creationComplete="initApp()">
<mx:Script>
<![CDATA[
public function initApp():void
{
Mouse.hide();
canvas.init();
canvas.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
}
private function keyDown(event:KeyboardEvent):void
{
canvas.KeyDownHandler(event);
}
]]>
</mx:Script>
<MyGameCanvas id="canvas" width="100%" height="100%" themeColor="#ff000000" />
</mx:Application>
...
package cyanprime{
import mx.core.UIComponent;
import mx.controls.Image;
import flash.events.*;
import flash.utils.*;
import flash.display.*;
import flash.ui.Keyboard;
public class MyGameCanvas extends UIComponent{
[Embed(source="player.gif")]
private var playerImage:Class;
private var player:DisplayObject = new playerImage();
private var player_x:Number;
private var player_y:Number;
private var ticker:Timer;
public function init():void{
// set up player
addChild(player);
ticker = new Timer(10);
ticker.addEventListener(TimerEvent.TIMER, onTick);
ticker.start();
}
public function KeyDownHandler(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.SHIFT)
player_x += 50;
}
public function onTick(evt:TimerEvent):void {
}
}
}
Solución
es necesario agregar al oyente a la etapa, y el anuncio que después del evento applicationComplete ha ocurrido (o en su controlador)
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
<mx:Script>
<![CDATA[
public function init():void
{
trace('Initialization');
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
}
private function keyDown(event:KeyboardEvent):void
{
trace(event.charCode);
}
]]>
</mx:Script>
</mx:Application>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow