Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Camera zoom?

Discussion in 'Scripting' started by Treasureman, Aug 8, 2014.

  1. Treasureman

    Treasureman

    Joined:
    Jul 5, 2014
    Posts:
    563
    I'm making an fps game and I'm having trouble with aiming. I want a script (JavaScript) so that when Fire2 is held down then the camera will zoom in

    Here's my script right now:

    Code (JavaScript):
    1. var zoom : int = 40; //<span class="fdx72e" id="fdx72e_12">determines</span> amount of zoom capable. Larger number means further zoomed in
    2. var normal : int = 60; //determines the default view of the camera when not zoomed in
    3. var smooth : float = 5; //smooth determines speed of <span class="fdx72e" id="fdx72e_10">transition</span> between zoomed in and default state
    4. private var zoomedIn = false; //boolean that determines whether we are in zoomed in state or not
    5. function Update () {
    6. if(Input.GetButton("Fire2")){        //This function toggles zoom capabilities with Fire2. If it's zoomed in, it will zoom out
    7. zoomedIn = !zoomedIn;
    8. }
    9. if(zoomedIn == true){    //If "zoomedIn" is true, then it will not zoom in, but if it's false (not zoomed in) then it will zoom in.
    10. camera.fieldOfView = Mathf.Lerp(camera.fieldOfView,zoom,Time.deltaTime*smooth);
    11. }
    12. else{
    13. camera.fieldOfView = Mathf.Lerp(camera.fieldOfView,normal,Time.deltaTime*smooth);
    14. }
    15. }
    Whenever I try to zoom the camera shakes violently and then zooms in when i let right Fire2 go. Can someone help? Thanks!
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Fraconte likes this.
  3. naked_chicken

    naked_chicken

    Joined:
    Sep 10, 2012
    Posts:
    186
    You need to use Input.GetButtonDown

    it shakes violently because GetButton fires every frame that the button is pressed so zoomedIn is getting toggled each frame. GetButtonDown only fires when you first press the button.
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667