# Character face direction of Camera

I’ve made a script for my character’s movement however I’ve come across the problem in which no matter which direction I face the camera the character doesn’t follow it and just keeps going in 1 direction. I’m currently using the default MouseLook C# script by unity for the camera.

Movement script:

``````public class PlayerMovement : MonoBehaviour {

public float playerSpeed = 5.0f;

// Update is called once per frame
void Update()
{

Vector3 vectorPosition = transform.position;//get position and put it back in

if (Input.GetAxis("Right Joystick Vertical") > 0f)
{

vectorPosition.z += playerSpeed * Time.deltaTime;

}

else if (Input.GetAxis("Right Joystick Vertical") < 0f)
{

vectorPosition.z -= playerSpeed * Time.deltaTime;

}

else if (Input.GetAxis("Right Joystick Horizontal") > 0f)
{

vectorPosition.x += playerSpeed * Time.deltaTime;

}

else if (Input.GetAxis("Right Joystick Horizontal") < 0f)
{

vectorPosition.x -= playerSpeed * Time.deltaTime;

}

else if (Input.GetKey(KeyCode.S))
{
vectorPosition.z -= playerSpeed * Time.deltaTime;

}
else if (Input.GetKey(KeyCode.W))
{
vectorPosition.z += playerSpeed * Time.deltaTime;

}

else if (Input.GetKey(KeyCode.A))
{
vectorPosition.x -= playerSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.D))
{
vectorPosition.x += playerSpeed * Time.deltaTime;

}

transform.position = vectorPosition;

}

}
``````

Another little bug I have with this code is that it only allows 1 action at a time. e.g. press W & A to go diagonally at a westerly angle ends up with character moving ignoring the A key and carrying on walking forwards.

To make the character look in the direction of your camera, you’ll have to use the camera’s y rotation and modify the player’s own rotation. I don’t have Unity available to me at this time, but it should look something like this:

``````public Camera targetCamera;

private void AlignToCamera() {
transform.rotation = Quaterion.Euler(transform.rotation.x, targetCamera.transform.rotation.y, transform.rotation.z);
}
``````

The only one action at a time is due to the use of ‘else if’ statements to handle the inputs. So if one of the ‘else if’ statements is true it will skip the following else if statements. Here’s a simple rewrite of your input handling code:

``````void Update()
{
Vector3 vectorPosition = transform.position;//get position and put it back in

if (Input.GetAxis("Right Joystick Vertical") > 0f || Input.GetKey(KeyCode.W)) {
vectorPosition.z += playerSpeed * Time.deltaTime;
}

if (Input.GetAxis("Right Joystick Vertical") < 0f || Input.GetKey(KeyCode.S)) {
vectorPosition.z -= playerSpeed * Time.deltaTime;
}

if (Input.GetAxis("Right Joystick Horizontal") > 0f || Input.GetKey(KeyCode.D)) {
vectorPosition.x += playerSpeed * Time.deltaTime;
}

if (Input.GetAxis("Right Joystick Horizontal") < 0f || Input.GetKey(KeyCode.A)) {
vectorPosition.x -= playerSpeed * Time.deltaTime;
}

transform.position = vectorPosition;
}
``````