Coding character movement in flash Action-Script 3.
This is part 2/2 of a tutorial for flash using action script 3. This is how I started to learn action script 3 after using action script 2 for 3 years.
Code:
import flash.events.KeyboardEvent;
import flash.events.Event;
var char:Char = new Char();
char.x = 250;
char.y = 255;
addChild(char);
var speed:Number = 5;
var leftButton:Boolean = false;
var rightButton:Boolean = false;
var upButton:Boolean = false;
var downButton:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kDown);
stage.addEventListener(KeyboardEvent.KEY_UP, kUp);
stage.addEventListener(Event.ENTER_FRAME, moveChar);
function kDown(event:KeyboardEvent){
if(event.keyCode == 37 || event.keyCode == 65){
leftButton = true;
}
if(event.keyCode == 38 || event.keyCode == 87){
upButton = true;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightButton = true;
}
if(event.keyCode == 40 || event.keyCode == 83){
downButton = true;
}
}
function kUp(event:KeyboardEvent){
if(event.keyCode == 37 || event.keyCode == 65){
leftButton = false;
}
if(event.keyCode == 38 || event.keyCode == 87){
upButton = false;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightButton = false;
}
if(event.keyCode == 40 || event.keyCode == 83){
downButton = false;
}
}
function moveChar(event:Event){
if(leftButton == true){
char.x -= speed;
}
else if(rightButton == true){
char.x += speed;
}
else if(upButton == true){
char.y -= speed;
}
else if(downButton == true){
char.y += speed;
}
}
Great job. a bit of constructive criticism. The umms and errmmm make it hard to follow your tutorial. Maybe override the audio with a replacement so it is a fluent narration. I am creating a game atm. with a character that moves towards screen using down or s. and gets smaller when walking opposide direction. would i use char.scale in the if statements? Plus there is obstables in the way how can i do collision detected with reference to this code?
thanks alot
ishaunay89 2 months ago
Very helpful, thankyou my friend. I am doing a uni assignment and your commentary helped with my understanding of as3 also. I was having trouble getting external as3 files to run but placing the coding in the layers is giving me no trouble.
SpringHeelMark 9 months ago
Wonderful! Thanks! I'm sure this could be optimized a bit, but it's good to see a completely reliable method. Cheers!
TheMoocowmoo 1 year ago