I’m using this movement script for camera-related third-person movement but it has been showing a weird behavior. When camera is at certain rotations (i’ve been testing this with continuously rotating for the sake of making it easier to happen) the character faces left after positive direction movement (left/down).
I wasn’t able to figure out why it’s happening so i decided to call for help. Here the code:
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float MoveSpeed = 6f;
public float TurnSpeed = 360f;
private Transform cam;
private Vector3 camMove;
private Vector3 movement;
private float turnAmount;
Rigidbody playerRigidbody;
void Awake () {
playerRigidbody = GetComponent <Rigidbody> ();
cam = Camera.main.transform;
}
void FixedUpdate () {
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
camMove = v * cam.forward + h * cam.right;
Move(camMove);
}
void Move (Vector3 move) {
move = transform.InverseTransformDirection (move);
turnAmount = Mathf.Atan2 (move.x, move.z);
transform.Rotate(0, turnAmount * TurnSpeed * Time.deltaTime, 0);
movement.Set (camMove.x, 0f, camMove.z);
movement = movement.normalized * MoveSpeed * Time.deltaTime;
playerRigidbody.MovePosition (playerRigidbody.position + movement);
}
}
Can anyone figure out why it occasionally faces left after movement?
Thanks.