Pages

Showing posts with label Ball Movement With Multi Keyboard Event. Show all posts
Showing posts with label Ball Movement With Multi Keyboard Event. Show all posts

Tuesday, May 1, 2012

Ball Movement With Multi Keyboard Event in ActionScript3.0




How to Identify Multi Key down in keyboard event?

here is Example:-

private var activeKeys:Object=new Object();

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpFunction);

private function onKeyDownFunction(event:KeyboardEvent):void
{
activeKeys[event.keyCode] = true;
}

private function onKeyUpFunction(event:KeyboardEvent): void
{
activeKeys[event.keyCode] = false;
}

now to easily find which key buttons are down in your Keyboard from activeKeys object.

this is the step for find key down:

activeKeys[Keyboard.LEFT] == true means left key arrow button is still key down.

activeKeys[Keyboard.LEFT]== false means left key arrow button is still key up. 


and now How to move the ball with use multi key event?

private var speedX:Number = 0;
private var speedY:Number = 0;
private var fricrion:Number = 0.95;
private var power:Number = 5;

ball_mc.addEventListener(Event.ENTER_FRAME, onRunningFunction);
/** here ball_mc is a MovieClip **/

private function onRunningFunction(event:Event):void
{
if (activeKeyContainer[Keyboard.LEFT])
speedX = -power;
if (activeKeyContainer[Keyboard.RIGHT])
speedX = power;
if (activeKeyContainer[Keyboard.UP])
speedY = -power;
if (activeKeyContainer[Keyboard.DOWN])
speedY = power;
/** friction apply for reduce the speed slowly **/
speedX *= fricrion;
speedY *= fricrion;
/**--------------------------------------------**/
ball_mc.x += speedX;
ball_mc.y += speedY;
/** avoid ball out of stage **/
if (ball_mc.x < ball_mc.width/2)
ball_mc.x = ball_mc.width / 2;
if (ball_mc.x > stage.stageWidth - ball_mc.width / 2 )
ball_mc.x = stage.stageWidth-ball_mc.width/2;
if (ball_mc.y < ball_mc.height / 2 )
ball_mc.y = ball_mc.height/2;
if (ball_mc.y > stage.stageHeight - ball_mc.height / 2)
ball_mc.y = stage.stageHeight-ball_mc.height/2;
/**------------------------**/
}

simply try it your system friends.

...CHeeRS...




click above demo and press up,down,left,right key board event.


         SourceFile