Tuesday, 4 October 2011

Classic keyboard navigation

Today we made a simple code for basic keyboard navigation.



stage.addEventListener(KeyboardEvent.KEY_DOWN, moveShip);


//This tells the program to look at the stage and listen out for any key pressed down, and if it is pressed down use function moveShip


function moveShip(myevent:KeyboardEvent):void {


//Name of the function

if (myevent.keyCode==Keyboard.RIGHT){
Ship.x+=5;
Ship.rotation=90;

}


//If the right key is pressed move the Ship 5 pixels along the x axis and rotate it to 90 degrees so it looks like this >

if (myevent.keyCode==Keyboard.LEFT){
Ship.x-=5;
Ship.rotation=270;
}


 //The same code but for when the left key is pressed but Ship moves to 270 degrees so it looks like this <


if (myevent.keyCode==Keyboard.UP){
Ship.y-=5;
Ship.rotation=0;
}


//Same code again but now it's rotated to 0 degrees which is default position ^


if (myevent.keyCode==Keyboard.DOWN){
Ship.y+=5;
Ship.rotation=180;
}
}


//And finally for down


stage.addEventListener(Event.ENTER_FRAME, bounds);


//Now we ask the program to 'listen' to the enter frame


function bounds(event:Event) {
if (Ship.x>=550) {
Ship.x=0;
}


//This tells the program that if 'Ship' is 550 or over pixels along the x axis (going off screen to the right) to move the ship back to 0 on the x axis (the far left)


if (Ship.x<0) {
Ship.x=550;
}
if (Ship.y>=400) {
Ship.y=0;
}
if (Ship.y<0) {
Ship.y=400;
}
}

//We then use the same code for the other sides so that when you move the Ship off the screen in any direction it re-appears at the opposite side

No comments:

Post a Comment