Player can only move forward and sideways. I want to also be able to move diagonally and backwards

Hi, I have a problem with my Third Person Movement Script. My player can only move forward and sideways, I want to also be able to move diagonally when pressing the sideways and backward or forward button.

Here’s the script:

public class CharacterMovement : MonoBehaviour
{

public CharacterController controller;

public Transform cam;

public float speed = 6f;

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;

    if (direction.magnitude >= 0.1f)
    {

        float targetAngle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg + cam.eulerAngles.y;

        Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
        controller.Move(moveDirection.normalized * speed * Time.deltaTime);

    }
}

}

I also have a Locomotion script, but it acts only as animation, as I had disabled “Apply Root Motion”

The issue is that you’re using the y component of your direction vector instead of the z,
it should be
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;