character turning left after camera-related movement
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.
Answer by ThatScar · Jul 22, 2016 at 08:49 PM
This might have something to do when your move
is zero and it's trying to calculate Mathf.Atan2 (0, 0)
. Try skipping the rotation part when the character isn't moving ( move != Vector3.zero
should work if you aren't moving in the y axis at all).
Answer by Lienn · Jul 22, 2016 at 10:30 PM
WTG! Just adding the if was enough to fix it! Thanks!
if (move != Vector3.zero) {
turnAmount = Mathf.Atan2 (move.x, move.z);
transform.Rotate (0, turnAmount * TurnSpeed * Time.deltaTime, 0);
}
Happy to be of use.
FYI you can add comments on answers and questions, good luck developing!
Your answer
