I’m not really sure what I did wrong here but I’m trying to make my character move relative to where the camera is facing but can’t seem to get it right. My character is able to turn its direction correctly but not move in the required direction.
e.g. pressing W makes him turn away from the camera but it only moves in the positive Z axis regardless of where the camera is facing
[SerializeField] private float magnitudeValue = 0.1f;
[SerializeField] private float moveSpeed;
[SerializeField] private float rotateSpeed;
[SerializeField] private Vector3 direction;
[SerializeField] private Vector3 moveDirection;
[SerializeField] private Transform cam;
[SerializeField] private Quaternion targetRotation;
[SerializeField] private Animator animator;
[SerializeField] private CharacterController characterController;
[SerializeField] private Rigidbody rb;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
direction = new Vector3(horizontal, 0f, vertical).normalized;
// if input for movement is detected
if (direction.magnitude >= magnitudeValue)
{
animator.SetBool("Walking", true);
// Atan2 finds angle between two axis from 0 to a vector
// adding camera angle in the end makes it so player moves relative to camera direction
// cam refers to ThirdPersonCamera game object
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
//transform.rotation = Quaternion.Euler(0f, targetAngle, 0f);
// character turn direction
moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
// move player using character controller
//characterController.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
}
else
{
animator.SetBool("Walking", false);
}
// rotate character to face input direction
if (moveDirection != Vector3.zero)
{
// specified rotation is created from LookRotation
targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
// change current rotation to specified target angle
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
}
}
void FixedUpdate()
{
rb.MovePosition(transform.position + direction * moveSpeed * Time.deltaTime);
}