Hi, Im very new to Gamedevelopment and currently Im doing my first Steps with Unity, but Im already facing a problem I can’t solve with my small knowledge and hope someone could help me a bit.
I have a GameObject which should be my Player and the normal MainCamera in a scene.
I want to let the camera follow my player in a way that I can move the player with the keyboard and look around the player with my mouse inputs. I already have a script thats working, but there is one issue I don’t understand. If I try to rotate above my player it works if I look straight forward, but if I rotate the player and try it again, the camera rotates beneath the player instead of rotating over it…
Im using this code:
Everything is working fine, only increaseCameraAngle is making problems, if I have rotated the player with updateCameraRotation before… If I didnt rotate first, the increase works fine… but after a rotation it increases to the left
PlayerController
void Update () {
listenUserInputs ();
}
private void listenUserInputs () {
float keyboardVertical = Input.GetAxis ("Vertical") * movementSpeed * Time.deltaTime;
float keyboardHorizontal = Input.GetAxis ("Horizontal") * movementSpeed * Time.deltaTime;
transform.Translate (keyboardHorizontal, 0, keyboardVertical);
mainCamController.updateHumanPosition (transform);
if (Input.GetMouseButton (0)) {
float mouseVertical = Input.GetAxis("Mouse X") * turningSpeed * Time.deltaTime;
transform.Rotate(0, mouseVertical, 0);
mainCamController.updateCameraRotation(mouseVertical);
}
if (Input.GetAxis("Mouse ScrollWheel") < 0) {
float mouseHorizontal = Input.GetAxis("Mouse ScrollWheel") * turningSpeed * 3 * Time.deltaTime;
mainCamController.decreaseCameraAngle(mouseHorizontal);
}
if (Input.GetAxis("Mouse ScrollWheel") > 0) {
float mouseHorizontal = Input.GetAxis("Mouse ScrollWheel") * turningSpeed * 3 * Time.deltaTime;
mainCamController.increaseCameraAngle(mouseHorizontal);
}
}
CameraController
void Update () {
if (humanPosition != null) {
transform.position = humanPosition.position + humanOffset;
transform.LookAt (humanPosition.position);
}
}
public void updateHumanPosition (Transform newPosition) {
this.humanPosition = newPosition;
}
public void updateCameraRotation (float newValue) {
humanOffset = Quaternion.AngleAxis (newValue, Vector3.up) * humanOffset;
}
public void increaseCameraAngle (float newValue) {
humanOffset = Quaternion.AngleAxis (newValue, Vector3.right) * humanOffset;
}
public void decreaseCameraAngle (float newValue) {
humanOffset = Quaternion.AngleAxis (newValue, Vector3.right) * humanOffset;
}