Flash CS3 – Using Arrow Keys To Move An Object






Copy and paste this AS3 code to the first frame of your flash CS3 document.

var UrShape:Shape = new Shape();
addChild(UrShape);
UrShape.x = 250;
UrShape.y = 150;
UrShape.graphics.lineStyle(3, 0x000000);
UrShape.graphics.beginFill(0x9900FF, 1);
UrShape.graphics.drawRect(0, 0, 50,50);
UrShape.graphics.endFill();
stage.addEventListener(KeyboardEvent.KEY_DOWN,MoveRectangle);

function MoveRectangle(keyEvent:KeyboardEvent):void {
switch (keyEvent.keyCode) {
case 37 ://left arrow
UrShape.x--;
break;
case 38 ://up arrow
UrShape.y--;
break;
case 39 ://right arrow
UrShape.x++;
break;
case 40 ://down arrow
UrShape.y++;
break;
default :
break;
}
}

Comments

Anjali said…
this works for one key at a time. what if i want to move the shape diagonally ?
Anil said…
Try this code

http://flash-workshop.blogspot.com/2010/04/control-car-movieclip-with-arrow-keys.html

Popular posts from this blog

AS3 - Access objects from external SWF files

Flash CS3 - XML Guestbook (AS3)

Flash CS4 - 3D Rotating Menu