0
votes

i need some help. im trying to make my character walk both direction(left and right) and an idle animation when standing still. i manage to make the character walk to the right and make the idle animation work. now if I copy the code from the right button to the left button, the walking animation gets stuck in the first frame on both direction. I tried to experiment with it but with no luck. im sorry if i sounded noob. i just started with studying programming.

here are the code that i used

RightBtn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(e:MouseEvent): void {
if(RightBtn){
    isRight = true;
}
}
RightBtn.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
function mouseUp(e:MouseEvent): void {
    if(RightBtn){
    isRight = false;
}
}

stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(Event){
    if(isRight==true && mcPlayer.x < 750){
    mcPlayer.x += 7;
    mcPlayer.gotoAndStop (2);
    mcPlayer.walkR.play ();
}
else{
    mcPlayer.gotoAndStop (1)
    mcPlayer.Idle.play ();
}
}

LeftBtn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown2);
function mouseDown2(e:MouseEvent): void {
if(LeftBtn){
    isLeft = true;
}
 }

LeftBtn.addEventListener(MouseEvent.MOUSE_UP, mouseUp2);
function mouseUp2(e:MouseEvent): void {
if(LeftBtn){
    isLeft = false;
}
}

stage.addEventListener(Event.ENTER_FRAME, loop2);
function loop2(Event){
if(isLeft==true && mcPlayer.x > 65){
    mcPlayer.x -= 7;
    mcPlayer.gotoAndStop (3);
    mcPlayer.walkL.play ();
}
else{
    mcPlayer.gotoAndStop (1)
    mcPlayer.Idle.play ();

}
}
1

1 Answers

0
votes

That's what you get from blatant copy&paste without learning the mechanics of how does it internally work. You set two listeners to stage, both altering mcPlayer regardless of whether it was already altered by the other one. So, you need to write both sets of code in one listener, and walk the code with your pen and paper to ensure that both isRight==true and isLeft==true branches work separately and don't interfere with each other. The proper condition statement should be like this:

if (isRight==true && mcPlayer.x < 750) {
    // do a step right
} else if (isLeft==true && mcPlayer.x > 65){
    // do a step left
} else {
    // do idle animation
}

Your codes of initiating animation are correct themselves, they just get overridden by the listeners that are unaware of some other code altering mcPlayer.