How do I make the movement relative to the camera?
I am trying to create my own third person controller using C#. Currently the players movements seem to be relative to the world rather than the camera. I want the movement to be relative to the camera, for example pressing the 'W' key will make the player move away from the camera. Any advice or solutions?
Here is my current script:
public class PlayerMovement : MonoBehaviour { public float movementSpeed = 10f; public float turningSpeed = 60f;
private CharacterController characterController;
void Start (){
this.characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
float horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
transform.Rotate(0, horizontal, 0);
this.characterController.transform.Rotate(0, horizontal, 0);
float vertical = Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime;
Vector3 movement = new Vector3(0, 0, vertical);
this.characterController.Move (movement);
}
}
Answer by Liraseth · Oct 09, 2019 at 07:07 PM
Ok I got this to work well with the help of other posts. Make sure that at the start of the script there is...
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
then the main part...
void FixedUpdate()
{
Vector3 movement;
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
GameObject cameraCompass = new GameObject("Camera Compass");
// "Correct" the compass so that it lies flat in the game plane
cameraCompass.transform.eulerAngles = new Vector3(0, GameObject.FindGameObjectWithTag("MainCamera").transform.eulerAngles.y, 0f);
Vector3 movementX = cameraCompass.transform.right * moveHorizontal;
Vector3 movementZ = cameraCompass.transform.forward * moveVertical;
movement = movementX + movementZ;
rb.AddForce(movement * speed);
Destroy(cameraCompass); // We don't need the Compass anymore!
}
Hopefully this helps!
Your answer
Follow this Question
Related Questions
How to have a child object camera with gaze move its parent object 0 Answers
Third person movement with fixed cameras 1 Answer
how to make forward relative to the view of the camera 0 Answers
How to make an object go the direction it is facing? (Im new) 0 Answers
Face direction of a Vector 3 1 Answer