Change Direction with Left/Right arrow

How can i move a sprite 2D, say Direction is up and left/right key to change its direction,
like classic snake but only allowed to change direction according to current moving direction…

Hmm… I guess you can use bool variables in order to check the state of the gameobject s’ direction then act accordingly, something like this for example:

bool leftState;
bool rightState;
bool upState;
bool downState;
//We'll assume the object points upwards by default
void Start(){
leftState = false
rightState = false;
downState = false;
upState = true;
}

void Update(){
if(Input.GetKeyDown(KeyCode.RightArrow)){
if(upState){
currDirection = Directions.Right;
DirVector = new Vector2(1,0);
upState = false;
rightState = true;
}
else if(rightState){
currDirection = Directions.Down;
DirVector = new Vector2(0, -1);
rightState = false;
downState = true;
}
else if(downState){
currDirection = Directions.Left;
DirVector = new Vector2(-1,0);
downState = false;
leftState = true;
}
else if(leftSate){
currDirection = Direction.Up;
DirVector = new Vector2(0, 1);
leftState = false;
upState = true; 
}
}
}

Same principle applies to the left arrow input, remember if you input the same arrow for 4 times in a row, the gameobject will be back to its original position, so you’re more or less turning around in circle, 4 times to return to the original position → 4 states → 4 bool variables. Hope this helps, tell me how it goes.

I’d probably create an ordered list (or array) of the possible directions (just some enum values). Something like:

List<Directions> DirectionList = new List<Directions>(){ Direction.Up, Direction.Right, Direction.Down, Direction.Left };

Then, when the right key is pressed…

  • Find the current direction in the above list.
  • The new direction will be the next item in the list. If the next item exceeds the number of items in the list, you just wrap it back to the beginning. So, if the current direction is “Left” (the last item), the new direction will be “Up” (the first item).

When the left key is pressed, you do exactly the same thing, but you’d traverse the list in reverse order. So…

  • Find the current direction in the list
  • The new direction will be the item that preceeds the current direction. If you attempt to move past the first item, just wrap that back to the end.

That should make the actual direction handling code nice and clean. Especially if you make a method that accepts the pressed key and the current direction and returns the new direction to the caller.

Jeff