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);
}