我已经在屏幕上显示了带有图像的图形,当我按下键盘上的箭头时我想移动它。
但看起来监听器没有运行且没有错误。
以下是代码:
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.display.BitmapData;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.net.URLRequest;
/**.
* ....
* @author Kaoru
*/
[SWF(width = '800', height = '600', backgroundColor = '#000000', frameRate = '24')]
public class GameManager extends Sprite
{
var myBitmap:BitmapData;
var imgLoader:Loader;
var circle:Sprite;
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function drawImage(e:Event):void
{
myBitmap = new BitmapData(imgLoader.width, imgLoader.height, false);
myBitmap.draw(imgLoader);
circle.graphics.beginBitmapFill(myBitmap, null, true);
circle.graphics.drawCircle(50, 50, 10);
circle.graphics.endFill();
addChild(circle);
}
private function onKeyDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
circle.x += 5;
}
else if (e.keyCode == Keyboard.RIGHT)
{
circle.x -= 5;
}
if (e.keyCode == Keyboard.UP)
{
circle.y += 5;
}
else if (e.keyCode == Keyboard.DOWN)
{
circle.y -= 5;
}
}
}
}
答案 0 :(得分:2)
您需要将其添加到stage
,就像这样,
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
我修改了你的代码:
请先检查ADDED_TO_STAGE
然后再继续,
public function GameManager():void
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); //This line is modified
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
答案 1 :(得分:1)
您是否尝试直接在舞台上添加听众?
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}