Trouble Implementing First Person Camera
I am trying to implement an FPS camera, but my rotation is broken for some reason. I am attaching this script on a camera called FPSCamera which is a child of the Player object tagged "Player". I used Debug.Log to make sure rotation{X,Y} was working properly, and it was printing out numbers. I want to move the player's rotation when moving in the X direction, and for the camera to move up and down when the mouse moves in the Y direction.
I am pretty new to this, so if my code looks off outside of the question, please critique me for that as well.
public class FpsCamera : MonoBehaviour {
private Quaternion playerRotation;
private Quaternion cameraRotation;
public float sensitivity = 100.0f;
void Start () {
cameraRotation = gameObject.GetComponent<Transform>().rotation;
playerRotation = GameObject.FindGameObjectWithTag("Player").transform.rotation;
}
void Update () {
float rotationX = playerRotation.eulerAngles.x + (Input.GetAxisRaw("Mouse X") * sensitivity);
float rotationY = cameraRotation.eulerAngles.y + (Input.GetAxisRaw("Mouse Y") * sensitivity);
cameraRotation = Quaternion.Euler(0f, rotationY, 0f);
playerRotation = Quaternion.Euler(rotationX, 0f, 0f);
}
}
EDIT: I forgot to mention, that I checked {camera,player}Rotation and they both were not equal to null
Answer by Glurth · Jun 07, 2017 at 05:26 PM
I see that you assign your computed rotation to the private variable cameraRotation, but I do NOT see you actually assigning it to the camera's transform's rotation: e.g.
gameObject.transform.rotation= cameraRotation;
Until you actually assign it to the object's transform, no changes will be visible. (Same for the player object.)
Great! I'll try this when I get home. So, when you get the component with GetComponent
, it doesn't automatically update the object? I just assumed it would since you can use GetComponent
on a Transform and it will update the position automatically.
When you get a component, you are getting a REFERENCE instance of a CLASS. When you modify it's values, you are doing it THROUGH the reference, modifying the original object.
Quaternions (and Vectors) however, are structs. This means when we access it, we are accessing the VALUE directly, not via a reference. Just like an int
, or a float
.
This is an important c# concept: https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx (or google search for "c# reference vs value")
Ahh, that makes sense. I didn't know quaternions/vectors were structs. Thanks!