Tuesday, 7 December 2010

Keyboard controls in AS3 part 3

In the Keyboard controls tutorial part 2 you could press two keyboard keys simultaneously to move the movie clip into any direction. The movement of the movie clip was however restricted to vertical and horizontal movements. In this post I will use some simple trigonometry to rotate the movement of the movie clip. If the angle of an object is known you can determine the dx and dy values (difference in horizontal and vertical positions) using the Math.cos and Math.sin.


Keyboard controls in AS3 part 3

Step 1

Open up the keyboard controls part 2 or alternatively create a movie clip using the Flash shapes tools. Then in your Actions panel enter the following code.

var speed:Number = 5.0;
var leftArrow:Boolean=false;
var rightArrow:Boolean=false;
var upArrow:Boolean=false;
var downArrow:Boolean=false;

//listeners 
addEventListener(Event.ENTER_FRAME, moveObject);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHit);
stage.addEventListener(KeyboardEvent.KEY_UP, noKeyHit);

//function to detect key press 
function keyHit(e:KeyboardEvent):void{
 if(e.keyCode == Keyboard.LEFT) leftArrow = true;
 if(e.keyCode == Keyboard.RIGHT) rightArrow = true;
 if(e.keyCode == Keyboard.UP) upArrow = true;
 if(e.keyCode == Keyboard.DOWN) downArrow = true;
}

//function to detected key release
function noKeyHit(e:KeyboardEvent):void{
 if(e.keyCode == Keyboard.LEFT) leftArrow = false;
 if(e.keyCode == Keyboard.RIGHT) rightArrow = false;
 if(e.keyCode == Keyboard.UP) upArrow = false;
 if(e.keyCode == Keyboard.DOWN) downArrow = false;
}

//rotates the movie clip when the left or right key is pressed and 
//moves the movie clip if the up or down key is pressed 
function moveObject(e:Event):void{
 if(leftArrow) block.rotation -=5;
 if(rightArrow) block.rotation +=5;
 if(upArrow) moveForward();
 if(downArrow) moveBackward();
}


function moveForward():void{
 var angle:Number = block.rotation * (Math.PI / 180);
 var dx:Number =  Math.cos(angle) * speed;
 var dy:Number =  Math.sin(angle) * speed;
 lemon_mc.x += dx;
 lemon_mc.y += dy;
}

function moveBackward():void{
 var angle:Number = block.rotation * (Math.PI / 180);
 var dx:Number =  Math.cos(angle) * speed;
 var dy:Number =  Math.sin(angle) * speed;
 lemon_mc.x -= dx;
 lemon_mc.y -= dy;
}

Note that the Math.cos and Math.sin require a value in radians so I have converted the degree into radians.


Step 2 

Export movie clip Ctrl + Enter. Now use your keyboard up or down key along with either the left or right key and the movie clip should rotate as well as move.

 

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP