While working on a simple third person camera and a character that can be moved around using direction keys, I encountered a strange issue:
When I press the left / right buttons, the character turns smoothly on the spot -ok.
When I press the forward button, the character moves forward -ok.
When I press both together, however (pressing forward for a couple of seconds, then the turn button to turn around while still walking), the turn key sometimes works, sometimes it doesn’t, resulting in a jerky character rotation.
I think the issue may be located in the character move script:
CharacterMove.js
#pragma strict
private var walkSpeed:float = 1.0;
private var gravity:float = 1.0;
private var moveDirection:Vector3 = Vector3.zero;
private var CharController:CharacterController;
// -------------------------------------------------------------
// START
// -------------------------------------------------------------
function Start()
{
CharController = GetComponent(CharacterController);
animation.wrapMode = WrapMode.Loop;
}
// -------------------------------------------------------------
// UPDATE
// -------------------------------------------------------------
function Update()
{
var axisH:float = Input.GetAxis("Horizontal");
var axisV:float = Input.GetAxis("Vertical");
// CAPSULE IS GROUNDED?
if (CharController.isGrounded == true)
{
// MOVE FORWARD (RUN / WALK)?
if (axisV > .1)
{
if (Input.GetButton("Run"))
{
animation["Walk"].speed = 1;
animation.CrossFade("Run");
walkSpeed = 6.0;
}
else
{
animation["Walk"].speed = 1;
animation.CrossFade("Walk");
walkSpeed = 2.0;
}
}
// MOVE BACKWARD?
else if (axisV < -.1)
{
animation["Walk"].speed = -1;
animation.CrossFade("Walk");
walkSpeed = 1;
}
// TURN?
else if (axisH)
{
if (!axisV) animation.CrossFade("Walk");
}
// NOTHING PRESSED?
else
{
animation.CrossFade("Idle");
}
// SET ROTATION AND MOVEMENT
transform.eulerAngles.y += axisH * 10.0; // TURN CHARACTER
moveDirection = Vector3(0,0,axisV); // MOVE CHARACTER
moveDirection = transform.TransformDirection(moveDirection);
}
// IN THE AIR -APPLY GRAVITY
else
{
moveDirection.y -= gravity * Time.deltaTime;
}
// ACTUALLY MOVE CHARACTER
CharController.Move(moveDirection * (walkSpeed * Time.deltaTime));
}