Wow! I really like your panda! Here's the code that fixes it:
ActionScript Code:
var leftKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var pandaSpeed:Number = 10;
// Listener - makes panda move based on key strokes that are down
mcPanda.addEventListener(Event.ENTER_FRAME, movePanda);
function movePanda(event:Event):void
{
if(leftKeyDown)
{
mcPanda.x -= pandaSpeed;
}
if(rightKeyDown)
{
mcPanda.x += pandaSpeed;
}
}
//Key down
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void
{
//Making booleans true bbased on keycode
if(event.keyCode == 37)
{
leftKeyDown = true;
if(mcPanda.currentLabel == "leftStop" || mcPanda.currentLabel == "rightStop")
{
mcPanda.gotoAndPlay("left");
}
}
if(event.keyCode == 39)
{
rightKeyDown = true;
if(mcPanda.currentLabel == "leftStop" || mcPanda.currentLabel == "rightStop")
{
mcPanda.gotoAndPlay("right");
}
}
if(mcPanda.x < mcPanda.width / 2)
{
mcPanda.x = 55;
}
else if(mcPanda.x > stage.stageWidth - mcPanda.width / 1.85)
{
mcPanda.x = stage.stageWidth - mcPanda.width / 1.85;
}
}
//Key up
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void
{
//Making booleans false based on keycode
if(event.keyCode == 37)
{
leftKeyDown = false;
mcPanda.gotoAndStop("leftStop");
}
if(event.keyCode == 39)
{
rightKeyDown = false;
mcPanda.gotoAndStop("rightStop");
}
}
Now for the explanation: The KEY_DOWN event listens for keys being pressed. That's obvious. But when you press and hold a key, you keep getting the event repeatedly, because of the key repeat rate of the operating system. It's not like a MouseEvent.CLICK event that happens once and it's over. To demonstrate, copy this code into a new fla file and run it:
ActionScript Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, downHandler);
function downHandler(event:KeyboardEvent):void {
if(event.keyCode == 37) {
trace("leftArrow");
}
}
Press and hold down the left arrow key. You'll get the trace statement, then a slight lag, then a whole bunch of trace statements. That's like what's happening with your panda: he (she?) walks briefly, then after that same lag kicks in, it keeps getting the same command repeatedly, either gotoAndPlay("left") or gotoAndPlay("right"). So imagine that you're holding down the left arrow key--your code is repeatedly telling it to gotoAndPlay("left") because of the key repeat rate.
In fact, the key repeat rate is why you'd want to use booleans in the first place, because pressing and/or releasing a key shouldn't do much more than set the corresponding boolean true or false.
New in AS3 is the "currentLabel" property, which comes in handy here. The above code checks to see if you're currently stopped on one of those two "stop" frames, and if you are, then and only then does it gotoAndPlay one of those sections. Hope that all makes sense.
Did I mention I really like that panda?