I want to make a moving character that runs a movie clip when a keyboard arrow is pressed.For example:
When no arrows are pressed I want the character not to move when any keyboard arrows are pressed and run a movie clip animation where the character runs when the right arrow is pressed and same with the left arrow.
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
movieClip_1.addEventListener(Event.ENTER_FRAME,fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
if (leftPressed)
{
movieClip_1.x -= 5;
}
if (rightPressed)
{
movieClip_1.x += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
}
My movie clips are: run_right
and run_left
.
My timeline:
Create a MovieClip called "movieClip_1".
var movieClip_1= new MovieClip_1();
Inside this MovieClip, add "run_right" animation on the first frame and "run_left" on the second frame.
I mean, add new MovieClips that contains your animations.
Then, go to fl_MoveInDirectionOfKey function and write this:
if (rightPressed)
{
movieClip_1.gotoAndStop(1);
}
else if (leftPressed)
{
movieClip_1.gotoAndStop(2);
}
else
{
// no animation
// movieClip_1.gotoAndStop(3); idle animation could be on frame 3
}