Search Unity

Resolved Why do i need to press each time twice on the mouse middle button to change the flag bool ?

Discussion in 'Scripting' started by Chocolade, Nov 27, 2022.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    Code (csharp):
    1.  
    2. public class ConeRotation : MonoBehaviour
    3. {
    4.    public float rotSpeed = 250;
    5.    public float damping = 10;
    6.  
    7.    private float desiredRot;
    8.    private bool autoRotate = false;
    9.  
    10.    // Start is called before the first frame update
    11.    void Start()
    12.    {
    13.        desiredRot = transform.eulerAngles.z;
    14.    }
    15.  
    16.    // Update is called once per frame
    17.    void Update()
    18.    {
    19.        if (Input.GetMouseButton(0))
    20.        {
    21.            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
    22.            else desiredRot += rotSpeed * Time.deltaTime;
    23.        }
    24.  
    25.        if (Input.GetMouseButton(1))
    26.        {
    27.            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
    28.            else desiredRot -= rotSpeed * Time.deltaTime;
    29.        }
    30.  
    31.        if (Input.GetMouseButton(2))
    32.        {
    33.            autoRotate = !autoRotate;
    34.        }
    35.  
    36.        if (autoRotate)
    37.        {
    38.            desiredRot += rotSpeed * Time.deltaTime;
    39.        }
    40.  
    41.        var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, desiredRot);
    42.        transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping);
    43.    }
    44. }
    45.  
    In this part i need to press the middle button of the mouse twice to change the flag either from false to true and then from true to false and i want to do it in one press/click on the middle button.

    Code (csharp):
    1.  
    2. if (Input.GetMouseButton(2))
    3.            {
    4.                autoRotate = !autoRotate;
    5.            }
    6.  
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,433
    The Input.GetMouseButton function returns true on *every* Update cycle until you let go. If you hold it down for 2 frames, your variable would toggle twice, making you think it had no effect. If you hold it down for 6 frames, no effect. If you happen to hold it down for an odd number of Update frames, like 7 frames, then the final value will have been toggled 7 times, and thus look like it was toggled once.

    You want Input.GetMouseButtonDown which only returns true on a single Update cycle when you first press the button, guaranteeing predictable toggly behavior.
     
    Chocolade likes this.