Add force relative to camera direction?

How could I set this up so that it adds the force relative to the camera’s direction instead of world? Currently have this attached to a ball object and slightly modified orbit script attached to camera.

function FixedUpdate () {
	var dir : Vector3 = Vector3.zero;
	
	dir.x = Input.GetAxis("Horizontal");
	dir.z = Input.GetAxis("Vertical");
	
	rigidbody.AddForce(dir * force);
}

I was thinking something like below, but that doesn’t seem to work.

function FixedUpdate () {
	var camdir : Vector3 = camera.forward;
	var dir : Vector3 = Vector3.zero;

	dir.x = Input.GetAxis("Horizontal");
	dir.z = Input.GetAxis("Vertical");
	
	var relativedir : Vector3 = Vector3.Cross(camdir, dir);
	rigidbody.AddForce(relativedir * force);
}

Edit: came up with this, it partially works. The only problem is that it doesn’t seem to like diagonal directions. If I rotate the camera 30 degrees to left and push forward, it will go towards 0 degrees. If I rotate camera 60 degrees and push forward, it goes towards 90 degrees.

function Update() {
	var camDir : Vector3 = Camera.main.transform.forward;
	
	
	var inputDir : Vector3 = Vector3.zero;
	inputDir.x = Input.GetAxis("Left_Horizontal");
	inputDir.z = Input.GetAxis("Left_Vertical");
	
	var dir : Vector3 = Vector3.zero;
	dir.x = camDir.x * inputDir.x;
	dir.z = camDir.z * inputDir.z;
	
	rigidbody.AddForce(dir * force);
}

Given that you have the transform of the camera, you can always use this-

var controlDirection : Vector3 = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
var actualDirection = cameraTransform.TransformDirection(controlDirection);

Then, you have camera-relative directions! You may want to flatten it to the x-z plane if you want your character to walk around flat, but you might not.

I know this was posted a long time ago, but just for others who might look here.

Change rigidbody.AddForce to rigidbody.AddRelativeForce

That should add force relative to your coordinate system

if (Mathf.Abs(Input.GetAxisRaw(“Vertical”)) + Mathf.Abs(Input.GetAxisRaw(“Horizontal”)) > 0.1f) {
Vector3 forward = Camera.mainCamera.transform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0, -forward.x);
float h = Input.GetAxis(“Horizontal”);
float v = Input.GetAxis(“Vertical”);

        Vector3 moveDirection = (h * right + v * forward);
        moveDirection = Quaternion.Inverse(this.transform.rotation) * moveDirection ;
        moveDirection = new Vector3(moveDirection.x, 0, moveDirection.z); 
        moveDirection = this.transform.rotation * moveDirection;