i want to change this camera zoom script

i found this script on here and it works and all but i want to change it to where it will zoom when i turn the wheel on my mouse, how do i do that.

//Camera zoom script

  // Camera
  var cam : Camera;

 function Update()
 {
     if(Input.GetButtonDown("Fire2"))
     {
        cam.fieldOfView = 30;
     }
     if(Input.GetButtonUp("Fire2"))
     {
        cam.fieldOfView = 60;
     }
 }

3 Answers

3
function Update(){
if( Input.GetAxis("Mouse ScrollWheel")>0){
    cam.fieldOfView = cam.fieldOfView + 5;
}
if( Input.GetAxis("Mouse ScrollWheel")<0){
    cam.fieldOfView = cam.fieldOfView - 5;
}
}

That should work, haven't tested, but if you understand scripting, should be able to figure it out =).

To accomplish zoom with the mouse wheel, you have to listen to Input.GetAxis("Mouse ScrollWheel"). :) It returns a float that indicates the direction you scrolled in. Scrolling up is positive, down is negative.

In my script, I'm using a fixed amount every time, so I'm not using the actual value of the float, just its sign to determine direction. I also needed to move the camera, not just change its FOV to zoom, so my script looked a little different than the below. I tried to modify it a little so it should match something like what you need.

The lerping is done over 5 frames to zoom smoothly instead of jumping the FOV back and forth the full amount. If you don't need smoothness, you can just add or subtract a fixed amount every time.

float mouseScrollDir = Input.GetAxis("Mouse ScrollWheel"); int lerpCounter = 6;

if (mouseScrollDir > 0) // Zoom in
{
    lerpCounter = 0;
    startFOV = cam.fieldOfView;
    endFOV = cam.fieldOfView - 30;
}
else if(mouseScrollDir < 0) // Zoom out
{
    lerpCounter = 0;
    startFOV = cam.fieldOfView;
    endFOV = cam.fieldOfView + 30;
}

if (lerpCounter < 6)
{
cam.fieldOfView = Mathf.Lerp(startFOV, endFOV, lerpCounter*0.2f);
    lerpCounter++;
}

Wow, I think you're the first person on this site that used Lerp in the way it's meant. Everyone uses the actual value as startvalue and a fix timestep (Time.deltaTime) but that causes the lerping to get slower at the end. That's also a nice effect but not "linear interpolation". Even worse if someone use slerp that way. That will completely "destroy" the advantage of slerp.

Thanks. :-D I can't take credit though, I had to research how it worked, and some other thread explained it to me the right way. If I were to be perfectionist about it, the lerpCounter should really start from 1 and not 0; otherwise, the first call to Lerp ends up setting cam.fieldOfView to the same as its start value. :P

Just a little simplification of Justin's version. It's not really better, faster or "the right way". It's just another way ;)

function Update(){
    cam.fieldOfView += 5 * Input.GetAxis("Mouse ScrollWheel");
}