Third person camera : follow and mouse wheel rotation
Hello,
I'm a beginner with C# and I try to make a Third Person camera that follow my character but also rotate around him when I click on Mouse Wheel.
Problem: I can't find a solution to do both.
This is the first version of my code. With this one, the camera follow my character and rotate, but with mouse mouvement (and i really don't like it)
public class PlayerCamera : MonoBehaviour {
public GameObject player;
private Vector3 offset;
[SerializeField] int rotationSpeed = 3;
[SerializeField] bool rotationCam = true;
void Start()
{
offset = transform.position - player.transform.position;
}
private void LateUpdate()
{
transform.position = player.transform.position + offset;
if(rotationCam)
{
Quaternion turnAngle = Quaternion.AngleAxis(Input.GetAxis("Mouse X")
* rotationSpeed , Vector3.up);
offset = turnAngle * offset;
}
transform.LookAt(player.transform);
}
}
And I find this one somewhere here. This one is perfect to rotate camera with mouse wheel, but don't follow my character.
using UnityEngine;
public class StreetViewCamera:MonoBehaviour {
public float speed = 3.5f;
private float X;
private float Y;
void Update() {
if(Input.GetMouseButton(0)) {
transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * speed, -Input.GetAxis("Mouse X") * speed, 0));
X = transform.rotation.eulerAngles.x;
Y = transform.rotation.eulerAngles.y;
transform.rotation = Quaternion.Euler(X, Y, 0);
}
}
}
Any help and/or suggestions on where to find some information to do both, would be much apprecieated :)
Answer by tormentoarmagedoom · Feb 05, 2020 at 11:59 AM
Hello there.
If the second code is working as you want for the rotation, you just need to add the "follow" part. This means change the transform.position of the camera according to character position. Whic is this line in the 1st code:
transform.position = player.transform.position + offset;
But, I don't know how is the camera configured in the hicheracy, i mean, if isa child of some other emptyobject, or child of the character, etc... You should try first.
A "trick" i do for this type of cameras, if to have an empty object (lets call it CameraBox) that always follow the character, is always at same coords as the character (center of the box is always the character). Then, this CameraBox have the camera as a child. The camera have some offset (from the center of the CameraBox) and is pointing the center of the box (also the character) so, everytime the box rotate, the camera is still pointing the character preserving the offset.
So you move and rotate the box, not the camera itself.
Good luck! Bye!
Answer by Polly_Barlow · Feb 05, 2020 at 04:23 PM
Wow, I'll never think it was that simple ! That works, thank you so much @tormentoarmagedoom !
Your answer
![](https://koobas.hobune.stream/wayback/20220612222747im_/https://answers.unity.com/themes/thub/images/avi.jpg)