I am trying to design my first flash game in unity I am have my player moving around but i don’t want it to be able to move diagonally and my code is allowing it.
package
{
import flash.display.*;
import flash.events.*;
import fl.motion.easing.Bounce;
public class Game extends MovieClip
{
//variables
private var player:Player; //code ref movie
private var speed:int; // referenc to speed
private var left:Boolean; // controles left
private var right:Boolean; // controles right
private var up:Boolean; // controles up
private var down:Boolean; // controles down
public function Game():void
{
// focus on the stage
stage.focus = stage;
// listen for keyboard events
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);// looking for key to be pressed down
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);// looking for key to be up
// creat the player
player = new Player(); // creates the new player
player.x = 300; // movement limits
player.y = 50; // movement limits
addChild(player);
// set the speed
speed = 10;
// main game loop
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
}
// game loop
public function gameLoop(event:Event)
{
//keep the player within the bounds
if(left == true)
{
if(player.x>20)
{
player.x = player.x - speed;
}
else if (player.x <20)player.x = 20;
}
if(right == true)
{
if(player.x < 580)
{
player.x = player.x + speed;
}
else if (player.x > 580) player.x = 580;
}
if(down == true)
{
if(player.y < 380)
{
player.y = player.y + speed;
}
else if(player.y > 380) player.y = 380;
}
if(up == true)
{
if(player.y> 20)
{
player.y = player.y - speed;
}
else if(player.y < 20) player.y = 20;
}
}
//key pressed
public function keyDownFunction(event:KeyboardEvent) // check if key is down
{
// go left
if(event.keyCode == 65) //looking for it to be pressed key code to use that key
{
left = true; // go left
}
// go right
if(event.keyCode == 68)//looking for it to be pressed key code to use that key
{
right = true; // go right
}
// go up
if(event.keyCode == 87)//looking for it to be pressed key code to use that key
{
up = true; // go up
}
//go down
if(event.keyCode == 83)//looking for it to be pressed key code to use that key
{
down = true; // go down
}
}
//key lifted
public function keyUpFunction(event:KeyboardEvent) // check to see if he has been released
{
if(event.keyCode == 65)//looking for it to be released key code to use that key
{
left = false; // dont go left
}
if(event.keyCode == 68)//looking for it to be released key code to use that key
{
right = false; // dont go right
}
if(event.keyCode == 87)//looking for it to be released key code to use that key
{
up = false; // dont go up
}
if(event.keyCode == 83)//looking for it to be released key code to use that key
{
down = false; // dont go down
}
}
}
}