[JS] Change camera distance to object

I played around with a camera zoom script for an FPS. New to Unity, I knew that child objects center on the parent, and assumed that by increasing the Z of the camera, it would move behind the character, which it did. I later learned that it doesnt move it back in relation to the character, it moves it in relation to the world.

Anyway, I wrote this:

var minFZoom: float = -4.1;
var maxZoom: float = 1.5;
var sensitivity: float = 13;

function Update () {
  var zoom: float = Camera.main.transform.position.z;
  
  if (Input.GetAxis("Mouse ScrollWheel") > 0)
  {Camera.main.transform.position.z = zoom - (0.01 * sensitivity);}
  
  if (Input.GetAxis("Mouse ScrollWheel") < 0)
  {Camera.main.transform.position.z = zoom + (0.01 * sensitivity);}
}

Obviously, this is wrong. I want the camera to remain behind the character. I just want it to move back and forth with the scroll wheel. How can I do this without using the Orthographic camera (which I don’t really get - just looks crazy to me)? I tried doing it via FOV but it’s not the effect I want.

You probably want to use the Translate function. It can move locally or by world. I think it moves locally by default. There is also a Vector3.forward, which sets it for you. Check the script reference.

I’ve done this and it works great. How can I set the min and max zoom for translate position though?

A nice way to set min and max is with the Math.Clamp function. However, you would need to actually use the distance from the player or something to clamp.