Hi all! Can someone tell me why my character controller is jittery when moving. This function handles the basic movement for the character, it’s being called from Update.
Control.cs
void UpdateMoveDirection(){
Vector3 forward = Camera.main.transform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0, -forward.x);
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
if(controller.isGrounded){ //If the controller is on the ground, move absolutely
v = vertical;
h = horizontal;
}
else{ //Else, we move smothly in air
v = Mathf.Lerp(v, vertical, Time.deltaTime * motionSmoothing);
h = Mathf.Lerp(h, horizontal, Time.deltaTime * motionSmoothing);
}
Vector3 targetDirection = h * right + v * forward;
targetDirection *= moveSpeed;
moveDirection.x = targetDirection.x;
moveDirection.z = targetDirection.z;
if(targetDirection != Vector3.zero && canMove){ //We smoothly rotate here if we canMove
Quaternion newRotation = Quaternion.LookRotation(targetDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotationSmoothing);
}
if(canMove)
controller.Move(moveDirection * Time.deltaTime);
if(controller.collisionFlags == CollisionFlags.Above)
moveDirection.y = -10.4f; //If we hit or heads, we stop moving upwards
if(moveSpeed >= maxMoveSpeed) //Limit our moveSpeed
moveSpeed = maxMoveSpeed;
}
Please let me know if you have any questions. Thank you!