Hi, I want to be able to make my player move forward in different directions depending on what direction the camera is facing, so say if by default my player moved north when I pressed W (W = forward), how could I make it that if my camera was facing east my player would follow in the east direction instead of the north? I will list my Camera and Movement script files below…
Camera file:
[Header("Variables")]
public Transform player;
[Space]
[Header("Position")]
public float camPosX;
public float camPosY;
public float camPosZ;
[Space]
[Header("Rotation")]
public float camRotationX;
public float camRotationY;
public float camRotationZ;
[Space]
[Range(0f, 10f)]
public float turnSpeed;
//Misc
public static bool CamOrbit = true;
private void Start()
{
offset = new Vector3(player.position.x + camPosX, player.position.y + camPosY, player.position.z + camPosZ);
transform.rotation = Quaternion.Euler(camRotationX, camRotationY, camRotationZ);
}
private void LateUpdate()
{
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * turnSpeed, Vector3.right) * offset;
transform.position = player.position + offset;
transform.LookAt(player.position);
}
Movement file:
//"rb" Is A Reference To Rigidbody
public Rigidbody rb;
//Internal Names To Change Values In Unity
public float forwardForce = 100f;
public float sidewayForce = 100f;
public float backwardForce = 100f;
//Controls For Player
void FixedUpdate ()
{
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, -backwardForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("d"))
{
rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}