2D Character Movement Issues

I have created a 2D player movement script that works perfectly, aside from one issue. When the character is facing left, the sprite continues to move right. I have a feeling it’s to do with the code starting with ‘if(Input.GetKeyDown(“left”))’.

The question: How do I make the sprite face left as well as move left, rather than facing left then going right?

Here is the full movement script:

#pragma strict

	var speed : float = 6.0;
	var jumpSpeed : float = 15.0;
	var gravity : float = 20.0;
	
	private var moveDirection : Vector3 = Vector3.zero;

function Start () 
{
}

function Update () 
{
	var controller : CharacterController = GetComponent(CharacterController);
	
	if(controller.isGrounded)
	{
		
		moveDirection = Vector3( Input.GetAxis("Horizontal"), 0, 0 );
		
		moveDirection = transform.TransformDirection ( moveDirection );
		
		moveDirection *= speed;
		
			if( Input.GetButton ("Jump"))
		{
			moveDirection.y = jumpSpeed;
		}	
	}
	
			if(Input.GetKeyDown("left"))
		{
			transform.rotation = Quaternion.Euler(0,180,0);
		}
			if(Input.GetKeyDown("right"))
		{
			transform.rotation = Quaternion.Euler(0,0,0);
		}
	
	moveDirection.y -= gravity * Time.deltaTime;
	controller.Move (moveDirection * Time.deltaTime);
}

Create a variable to determine which direction you are facing (not in the update function):

private var faceDirection : int; //0 = right, 1 = left

Then, set it when you change directions:

    if(Input.GetKeyDown("left"))
		{
			faceDirection = 1;
			transform.rotation = Quaternion.Euler(0,180,0);
		}
    if(Input.GetKeyDown("right"))
		{
			faceDirection = 0;
			transform.rotation = Quaternion.Euler(0,0,0);
		}

Lastly, when you are updating your movement, check which direction you are facing. Return a positive when facing right, and a negative when facing left:

		 if (faceDirection == 0)//facing right
			{
				moveDirection = Vector3( Input.GetAxis("Horizontal"), 0, 0 );
			}
		else if (faceDirection == 1)//facing left
			{
				moveDirection = Vector3( -Input.GetAxis("Horizontal"), 0, 0 );
			}

Hope that helps :slight_smile: