Hi! I have a game in which a character moves in first person using WASD, and the camera rotation is controlled by the mouse. The problem is that the character moves based on the XYZ coordinates, and not the camera’s rotation. How do I make it so that W moves the player forward based on the direction the camera is facing?
Here is my code connected to the camera:
using UnityEngine;
using System.Collections;
public class FirstPersonCam : MonoBehaviour
{
public float speedH = 2.0f;
public float speedV = 2.0f;
private float yaw = 0.0f;
private float pitch = 0.0f;
void Update ()
{
yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
}
}
Here is my code connected to the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collide : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
GetComponent<Rigidbody>().velocity = new Vector3 (Input.GetAxis("Horizontal") * 5, 0, Input.GetAxis("Vertical") * 5);
}
}
I’m new to Unity, so sorry if this is a stupid question.
I posted this question before, but I didn’t get any answers I really knew how to use. I don’t know Unity too well, so if you guys could tell me exactly what and where to put code, that would be helpful, thanks!
Probably the simplest method you could use is to just use the Camera’s Transform, and use
GameObject cameraReference = Camera.main;
Vector3 forwardMovement = cameraReference.transform.forward;
forwardMovement.y = 0f;
forwardMovement = forwardMovement.normalized; // the forward direction in a vector form
This takes whatever direction the camera is facing, flattens it down, and normalizes it so it’s of length 1. No geometry needed, although calculating the angles through geometry might be more efficient.