Hello there! I just recently got flash CS4 and was wondering how you can actually make characters move in ActionScrpt 3. I know you are probably thinking..."OMG you know there is something like google!" but I rather get help from people instead of some tutorials and so that I can ask questions back. I have some code but I'm not sure if this is AS2 or AS3. If it does happen to be AS2, can anyone tell me how make the code in AS3? ///////////////////////////////////////////////////////////////////// var walkSpeed:Number = 5;
The code you have is AS2 and The basic way to do in AS3 is like that:
//let's say you have a charcter named hero, he will be moved
//you'll need some boolean variables to store if the key is pressed //or not and a velocity variable just to explain var velocity:Number = 4 var leftKeyDown:Boolean; var rightKeyDown:Boolean; var upKeyDown:Boolean; var downKeyDown:Boolean;
//now you'll need 2 events to "listen" if the key is pressed or if //it is released stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
//and finnaly you'll need an ENTER_FRAME event to check for the //variables and move addEventListener(Event.ENTER_FRAME, moveHero);
function onKeyDown(e:KeyboardEvent) { switch(e.keyCode) { case 37: leftKeyDown = true; break; case 38: upKeyDown = true; break; case 39: rightKeyDown = true; break; case 40: downKeyDown = true; break; } } function onKeyUp(e:KeyboardEvent) { switch(e.keyCode) { case 37: leftKeyDown = false; break; case 38: upKeyDown = false; break; case 39: rightKeyDown = false; break; case 40: downKeyDown = false; break; } }
//The function that moves the hero function moveHero(e:Event):void { if(upKeyDown) { hero.y -= velocity; } if(downKeyDown]) { this.y += velocity; } if(rightKeyDown) { this.x += velocity; } if(leftKeyDown) { this.x -= velocity; } }
WOW dude thank you soooooo much for this code....but I have a question...aren't you supposed to do something like hero._y? Or is that "_" taken away in AS3? I'm new to Flash so it could take me a while to show you the final .swf file on some other site :}!
I've checked the documentation, since I've never really used AS2 and you are right. The property " _y , _x " are the y and x coordinates of a movie clip relative to the local coordinates of the parent movie clip in AS2.
And the " x , y " public properties or atributes, since we are in the OOP world now =p, indicates the x and y coordinates of the DisplayObject instance (your hero) relative to the local coordinates of the parent DisplayObjectContainer (in this case, the stage) in AS3.