PDA

View Full Version : [AS3] Character Animation tied to Key Press



game2create
September 17th, 2010, 03:10 PM
I am trying to make a platform game, a new concept for me. So, I'm tackling this project one step at a time. I created a character with animated states that reacts to pressed buttons (e.g. walking, jumping).

I was able to get the character to react but it won't animate. It only plays the first frame of the animation for the walk cycle when facing right. When facing left, the character stands still and the walk cycle won't run. The idle animation also doesn't play. I've been trying to solve my problem from a book I bought but no dice.



//stop();

var Block_mc:Hero = new Hero();
var dir:Number=1;
var faceLeft, leftArrow, rightArrow:Boolean=false;

addChild(Block_mc);
placeHero(144,216);

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownCheck);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpCheck);

//FUNCTIONS
function placeHero(aNum:Number,bNum:Number) {
Block_mc.x=aNum;
Block_mc.y=bNum;

Block_mc.addEventListener(Event.ENTER_FRAME, moveHero);
}
function keyDownCheck(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow =true;
} else if (event.keyCode == 39) {
rightArrow = true;
}
}
function keyUpCheck(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
}
}
function moveHero(event:Event) {
if (leftArrow) {
if (!faceLeft) {
Block_mc.scaleX*=-1;
faceLeft=true;
}
Block_mc.gotoAndPlay("walk");
}
if (!leftArrow) {
Block_mc.gotoAndPlay("norm");
}
if (rightArrow) {
if (faceLeft) {
Block_mc.scaleX*=-1;
faceLeft=false;
}
Block_mc.gotoAndPlay("walk");
}
if (!rightArrow) {
Block_mc.gotoAndPlay("norm");
}
}


The character has only two lines of code inside of it:



this.gotoAndPlay("norm");
this.gotoAndPlay("walk");


Appreciate help on this. I've done simple point-and-click games before but this is really giving me a headache.

bluemagica
September 17th, 2010, 03:25 PM
your problem is you are telling it to go and play the animation every frame, so it does "go" to the frame, but doesn't get time to "play" it. so before calling this.gotoAndPlay("walk") or something, check if(this.currentLabel!="walk") , which basically means, if I am not already on the walk animation, only then go and play it, else just continue playing it.

foryou.sandeep
September 21st, 2010, 12:54 AM
another problem i think is, u r adding "norm" and "walk" together. if u r pressing the right key, then 2nd and 3rd conditions will be true.

Use "else if" and mix 2nd 4th condition and place it at the end.

game2create
October 1st, 2010, 09:10 AM
Big Thanks to Bluemagica and foryou.sandeep. Took a little while and finally got the code working.