So some time ago I was working on a 3rd person controller and I’ve recently decided to start again from scratch.
I’ve positioned a camera target slightly above the player’s head and the cam is currently looking at it using the LookAt function that I’m intending to replace by some self-made code later on. I simply move it around the player using the transform.Translate function.
transform.LookAt(camTarget);
float horizontal = Input.GetAxis("Mouse X") * moveSpeed * Time.deltaTime;
float vertical = Input.GetAxis("Mouse Y") * moveSpeed * Time.deltaTime;
transform.Translate(horizontal, -vertical, 0f);
So that way, it works out pretty well except that the distance between the camera and the player keeps increasing when moving the cam around, possibly because the LookAt function can’t keep up with the cam’s translation.
So I tried to fix it by subtracting the desired offset from the actual cam’s distance to the player and add that value to the cam’s local z-axis in order to move it back towards the player. And it works, if you move the cam really slowly. The distance always gets adjusted to my offset variable.
camDistance = Distance(transform.position, camTarget.position); // I know there's a Unity distance function but I've made that one myself
float zFix;
if(camDistance > camOffset){
zFix = transform.localPosition.z + (camDistance - camOffset);
transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, zFix);
}
However, if you move the cam a bit faster, the Debug.Log distance output increases incredibly fast, ending up displaying “Infinity”.
Pausing the scene doesn’t let you focus on the camera anymore, which I guess means that Unity completely lost track of where it is.
It just flies off into infinity.
I haven’t got any idea so far why this is happening since the code is rather simple.
Soo… hope some of you can help me out.
Best regards.
PS: All the code above is in LateUpdate().