所以我对Actionscript 3有点新意,如果我错过了一些对解决至关重要的事情,请告诉我,我会发布,但无论如何......
所以我有2层。顶层是内容,底层是as3(用于actionscript)。在我的内容中,我有一个小蓝球。在舞台的中心。在我的as3层中,我有以下代码:
//Add the event listeners...
stage.addEventListener(Event.ENTER_FRAME, moveBall);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keypress);
stage.addEventListener(KeyboardEvent.KEY_UP, keyrelease);
//Movement variables...
var velY;
var velX;
var power = 5;
var friction = 0.95;
//Key variables...
var right;
var left;
var up;
var down;
function keyrelease(event:KeyboardEvent) {
right = false;
left = false;
down = false;
up = false;
}
function keypress(event:KeyboardEvent) {
if (event.keyCode == 39) {
right = true;
}
if (event.keyCode == 37) {
left = true;
}
if (event.keyCode == 38) {
up = true;
}
if (event.keyCode == 40) {
down = true;
}
}
function moveBall(event:Event) {
if (right == true) {
velX += power;
}
if (left == true) {
velX -= power;
}
if (up == true) {
velY += power;
}
if (down == true) {
velY -= power;
}
character.x += velX;
character.y += velY;
velY *= friction;
velX *= friction;
}
基本上我正在做的是检查按键是否被按下,如果是这样,我会使velY或velX等于以某种方式递增小蓝球,并且velY和velX将继续减小直到(因为舍入误差)它变为零,蓝色球停止。但是,没有任何关键功能,因为某些原因,我的小蓝圈位于屏幕的左上角。
答案 0 :(得分:0)
那是因为你没有初始化速度变量。它们是无类型的,因此它们的初始值为undefined
。
在这些行中,它们会自动提升为Number
character.x += velX;
character.y += velY;
强制undefined
到Number
时,它变为NaN
(不是数字)。因此,生成的坐标为NaN
。 FlashPlayer通过将DisplayObject
设置为0来响应此问题。
另外,我建议使用flash.geom.Point
(善于操纵坐标),flash.ui.Keyboard
(更具可读性)和flash.utils.Dictionary
(而不是使用许多标记和ifs,构建查找地图)。
//Add the event listeners...
stage.addEventListener(Event.ENTER_FRAME, moveBall);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keypress);
stage.addEventListener(KeyboardEvent.KEY_UP, keyrelease);
//Movement variables...
const power:Number = 5;
const friction:Number = 0.95;
var velocity:Point = new Point();
var map:Dictionary = new Dictionary();
map[Keyboard.LEFT] = new Point(-power, 0);
map[Keyboard.UP] = new Point(0, -power);
map[Keyboard.RIGHT] = new Point(power, 0);
map[Keyboard.DOWN] = new Point(0, -power);
var acceleration:Dictionary = new Dictionary();
function keyrelease(event:KeyboardEvent):void {
delete acceleration[map[event.keyCode]];
}
function keypress(event:KeyboardEvent):void {
var p:Point = map[event.keyCode];
if (p) acceleration[p] = p;
}
function moveBall(event:Event):void {
for each (var p:Point in acceleration) velocity = velocity.add(p);
character.x += velocity.x;
character.y += velosity.y;
velocity.normalize(velocity.length * friction);
}
答案 1 :(得分:0)
由于未定义velY和velX,因此当您尝试添加或减去它时会产生意外结果。首先使用
定义它们CRAP