How to convert a direction Vector3 from world to local space

I am trying to make a custom 3rd person controller with Javascript.

I am getting float values from the axes of an analog stick (Xbox controller):

    function Update() {
           var moveX:float = Input.GetAxis("LeftStickX");
           var moveY:float = Input.GetAxis("LeftStickY");
    }

And I am using these floats to determine which direction my character needs to face:

function FixedUpdate() {
        if(moveX || moveY){
                  var direction:Vector3 = new Vector3(moveX, 0, -moveY);
                  //direction = cam.transform.InverseTransformDirection(direction);
                  transform.forward = direction;
        }
}

This works great, but only from one camera angle. Since “direction” is in the world space, it doesn’t match up with whatever direction my camera may be facing.

If I can just convert “direction” from world space to the camera’s local space, I should be able to control the character from many different camera angles.

Does anyone know how I can do this easily?

I tried using the commented-out line 4, which almost worked, except the x and z values of “direction” were reversed when my camera was facing east or west. (“cam” is the gameObject where my camera is stored)

Try this (not tested and I write in C# so I may have made typos!):

 function FixedUpdate() {
         if(moveX || moveY){
                   var direction:Vector3 = new Vector3(moveX, 0, -moveY);  // Think of this as the dir in camera space
                   var t:Transform = cam.transform;   // Make a local copy so we can change it
                   t.position = Vector3.zero;  // We don't care about the position, only the orientation
                   direction = t * direction;  // Transform dir into world space
                   direction.y = 0.0f;  // Zero Y component so that facing is guaranteed to be horizontal even if camera is raised (unless directly overhead...but avoid that ;)
                   transform.forward = direction;
         }
 }