Most questions want to rotate an object around an axis. But I need to rotate all three axis accordingly around to the rotation of the camera. This is due to the fact I want to mimic most first person shooters: if you press the key to go forward, you go forward relative to where you’re facing not the axis. For example, if I turn my camera to the left 90 degrees and I press the forward button (up arrow), the camera moves forward… as if it didn’t turn at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
public float speed;
public GameObject projectile;
public GameObject hit_object;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.RightArrow))
{
transform.localPosition += Vector3.right * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += Vector3.left * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position += Vector3.back * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += Vector3.forward * Time.deltaTime * speed;
}
if (Input.GetKeyDown(KeyCode.F))
{
GameObject bullet = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
bullet.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0, 0, 2000));
}
if (Input.GetKeyDown(KeyCode.E))
{
var pos_x = transform.position.x + Random.Range(-500F, 500F);
var pos_z = transform.position.z + Random.Range(-500F, 500F);
Instantiate(hit_object, new Vector3(pos_x, 400, transform.position.z + pos_z), Quaternion.identity);
}
transform.Rotate(0f, Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0f, Space.World);
transform.Rotate(-Input.GetAxis("Vertical") * speed * Time.deltaTime, 0f, 0f, Space.Self);
}
}
In the above snippet, the camera is facing in the direction of the red arrow and thus expect it to move forward in that direction. Instead, it moves according the y-axis (blue arrow). How do I fix this problem?