我是Actionscript 3的新手,我想让一个圆圈使用键盘上的向下箭头向下移动。这是我的代码:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Circle extends MovieClip {
public function Circle() {
// constructor code
var speed:int = 3;
addEventListener(KeyboardEvent.KEY_DOWN,keyIsDown);
function keyIsDown(event:KeyboardEvent) {
if(event.keyCode == Keyboard.DOWN) {
y = y+=speed;
}
}
}
}
}
当我测试它时,按下向下键时没有任何反应。有人知道代码有什么问题吗?
答案 0 :(得分:2)
尝试将KeyBoard事件添加到舞台而不是类。另外,我不会像这样嵌套函数,一般来说是不好的做法。第y = y+=speed;
行也很混乱,不应该只是y += speed;
吗?
编辑:对不起,我猜在构造函数中stage将为null,我添加了一个ADDED事件监听器。
试试这个:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Circle extends MovieClip {
public function Circle() {
// constructor code
var speed:int = 3;
addEventListener(Event.ADDED, onAdded);
}
private function onAdded(event:Event) {
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyIsDown);
}
private function keyIsDown(event:KeyboardEvent) {
if(event.keyCode == Keyboard.DOWN) {
y += speed;
}
}
}
}