So I’m a little new to Actionscript 3 and if I’m missing something crucial to solving just tell me and I will post it, but anyways…
So I have 2 layers. The top layer is content and the bottom layer is as3 (for actionscript). In my content I have a little blue ball that is approx. in the center of the stage. And in my as3 layer I have the following code:
//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;
}
Where basically what I am doing is check if a key is pressed and if so I make velY or velX equal powe that will increment the little blue ball a certain way and velY and velX will keep decreasing until (because of rounding errors) it becomes zero and the blue ball stops. But, nothing is working with the keys, and for some reason my little blue circle is in the upper left most corner of the screen.
That is because you don’t initialize the velocity variables. The are untyped, thus their initial value is
undefined.In these lines they are automatically promoted to
NumberWhen coercing
undefinedtoNumberit becomesNaN(not a number). Thus the resulting coordinates areNaN. FlashPlayer responds to this by putting theDisplayObjectto 0.Also, I’d suggest using
flash.geom.Point(good to manipulate coordinates),flash.ui.Keyboard(is far more readable) andflash.utils.Dictionary(rather than having many flags and ifs, build lookup maps).