Moving Object usning key board in Flash AS 3.0


Hi,

Here I am writing about Moving object to front and back like car moment, so, here user can move object to front or back only and he can rotate :).


To do this we should need to know "Finding Keyboard Key Code", "converting degrees to radinas","Use of Math.cos,Math.sin trigonometry functions".


Object Moving Formula:

angle=obj.rotation;
radians = angle * Math.PI / 180;
vx = Math.cos(radians) * speed;
vy = Math.sin(radians) * speed;



In above code "obj" is object which one trying to move,  "angle" is a variable it contains rotation of object in degrees, "radians" contains rotation of object in radians.

"vx" is velocity in x direction of object, "vy" is velocity in y direction of object.


To convert degrees to radians we have to use formula " radinas=degrees*Math.PI/180".

I have used same formula to find "obj" rotation in radians.

Upto here you learn how to find velocity of object. Now we can write code to move object depends upon the key board.


To process a function when key press in Key board, we should use "KeyboardEvent.KEY_DOWN".


var keyleft,keyright,keyup,keydown:Boolean=false;




stage.addEventListener(KeyboardEvent.KEY_DOWN, down);
stage.addEventListener(KeyboardEvent.KEY_UP, up);
stage.addEventListener(Event.ENTER_FRAME, loop);


function down(event:KeyboardEvent)
{
if(event.keyCode==37)
{
keyleft=true;
}

if(event.keyCode==38)
{
keyup=true;
}

if(event.keyCode==39)
{
keyright=true;
}

if(event.keyCode==40)
{
keydown=true;
}
}


function up(event:KeyboardEvent)
{
if(event.keyCode==37)
{
keyleft=false;
}

if(event.keyCode==38)
{
keyup=false;
}

if(event.keyCode==39)
{
keyright=false;
}

if(event.keyCode==40)
{
keydown=false;
}
}


Following are key codes for left,right,up,down Keys:

left=37, right=39, up=39, down=40

So, following code for when you press "Left Key" then "keyleft" boolean variable will be true, same for right,up,down keys.


Folliwng code for movement object when "leftkey or rightkey or upkey or downkey" are "true":



var angle,radians,vx,vy=0;
var speed=2;
function loop(event:Event)
{
angle=obj.rotation;
radians = angle * Math.PI / 180;
vx = Math.cos(radians) * speed;
vy = Math.sin(radians) * speed;

if(keyleft){
obj.rotation--;
}

if(keyright){
obj.rotation++;
}

if(keyup){
obj.x += vx;
obj.y += vy;
}

if(keydown){
obj.x -= vx;
obj.y -= vy;
}
}




Just copy and paste following codes into your flash document in first frame, and create a movieclip object with name "myObj", then you will get out put.



I hope you all enjoy......... :)


Thanks,
K sWamy Vishnubhatla,
swamy.webdesigner@gmail.com.