Third Person Strafe controls

So ive recently picked up Unity for making a tiny personal project for the sake of fun, followed a quick tutorial for a third person movement script and have been discussing it with friends, the problem with the movement script is that the player’s forward angle follows its movement direction rather than the camera, and i’d like to have strafing instead.

Code for reference:

public class thirdpersonmovement : MonoBehaviour
{
    public CharacterController controller;
    public Transform cam;

    public float speed = 6f;

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;

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

        if(direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

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

Any help would be appreciated, oh also any help with setting up gravity would be appreciated.

By default CharacterController turns to face the direction you tell it, and CharacterController does not inherently support gravity.

If you want one that supports gravity, check out this patched one:

If you want to fundamentally change how your controls are mapped, it might be better to just start from another tutorial that does NOT turn to face motion. Character movement is such a trivial quick piece of code to set up once you have done three or four of them, it’s not worth trying to “convert” one into another; you’ll just make a mess of it all.

At that time you may wish to consider a Rigidbody-based controller, as Rigidbody can take care of gravity for you at the same time.

Rigidbody and Character Controller are generally NEVER mixed.

I cant believe ive been that stupid, thanks for the help

for strafe you change the animation state played (and not use that part of the code. I would make a mode [enum. sg like strafe / turntoside] for sideway input.)

basically its just connecting input with animation state. (you can do it with mecanim trigger/flowchart, crossfade, blendtree…). I don’t know what what would be suitable for CharacterController, since not using it, but it’s up to how you script it. I would not tie up the movement with camera pos, though