Changing movement based on camera direction

Hi

I’m sitting here contemplating a way to solve a rather difficult (to a newbie like myself) problem; I have a script that moves a player around. I also have a camera that can rotate based on mouse movement. However I would always want the forward from the camera to be the forward of the movement for the player. As far as Ive come is to maybe draw a ray from the camera transform and to the player transform. That direction is always the forward direction. Would this be correct? How would I this change the player movement? I have no idea how to tackle it :frowning:

var MoveSpeed : float;

function Update () 
{
	// MOVEMENT
	translationVertical = Input.GetAxis ("Vertical");
	translationVertical = translationVertical * MoveSpeed;
	translationVertical *= Time.deltaTime;
	rigidbody.position -= Vector3(0,0,translationVertical);

	translationHorizontal = Input.GetAxis ("Horizontal");
	translationHorizontal = translationHorizontal * MoveSpeed;
	translationHorizontal *= Time.deltaTime;
	rigidbody.position -= Vector3(translationHorizontal,0,0);
}

You need to convert from the camera’s local space to world space. A simple way to do this is by using TransformDirection.

If your camera is looking down you might need to compensate for that, like dropping the y component of the final direction and normalizing it before applying the speed multiplication.

Thank you very much Jasper, I now got it working exactly like I want it. In case someone else stumbles upon this post, this is how the movement code ended like. Oh and dont forget to get a reference to the camera (the camera look script is not included as it was not written by me).

translationVertical = Input.GetAxis ("Vertical");
translationVertical = translationVertical * MoveSpeed;
translationVertical *= Time.deltaTime;

translationHorizontal = Input.GetAxis ("Horizontal");
translationHorizontal = translationHorizontal * MoveSpeed;
translationHorizontal *= Time.deltaTime;

var cameraRelative : Vector3 = theCamera.main.transform.TransformDirection (0, 0, -1);
rigidbody.position -= Vector3((cameraRelative.x * translationVertical), 0,(cameraRelative.z * translationVertical) );
cameraRelative = theCamera.main.transform.TransformDirection (-1, 0, 0);

rigidbody.position -= Vector3((cameraRelative.x * translationHorizontal), 0,(cameraRelative.z * translationHorizontal) );

Very nice. I personally like to move characters as ridigbodies with forces.

var speed : float = 5.0;
var movementVector : Vector2 = Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
var force = speed * movementVector.magnitude;
var direction : Vector3 = movementVector.y * mainCamera.forward + movementVector.x * mainCamera.right;
       
rigidbody.AddForce(direction * force);