You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中鼠标中键切换autoRotate需双击问题求助

解决鼠标中键点击切换autoRotate状态首次无效的问题

问题出在你使用的鼠标输入API上:当前代码里的Input.GetMouseButton(2)会在鼠标中键按住的每一帧都执行状态翻转逻辑,第一次点击按住时,autoRotate = !autoRotate会在极短时间内被反复执行几十上百次(取决于游戏帧率),最终又回到初始的false状态,肉眼看起来就像没触发切换;第二次点击时同理,只是初始状态变为false,多次翻转后最终停在true,所以看起来只有第二次点击生效。

要实现每次点击鼠标中键只切换一次状态,把Input.GetMouseButton(2)替换成Input.GetMouseButtonDown(2)即可——这个API只会在按键按下的第一帧触发一次,完全匹配你的需求。

修改后的关键代码片段:

if (Input.GetMouseButtonDown(2))
{
    autoRotate = !autoRotate;
}

完整修改后的代码:

public class ConeRotation : MonoBehaviour
{
    public float rotSpeed = 250;
    public float damping = 10;

    private float desiredRot;
    private bool autoRotate = false;

    void Start()
    {
        desiredRot = transform.eulerAngles.z;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot += rotSpeed * Time.deltaTime;
        }

        if (Input.GetMouseButton(1))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot -= rotSpeed * Time.deltaTime;
        }

        // 改用GetMouseButtonDown实现单次点击切换
        if (Input.GetMouseButtonDown(2))
        {
            autoRotate = !autoRotate;
        }

        if (autoRotate)
        {
            desiredRot += rotSpeed * Time.deltaTime;
        }

        var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, desiredRot);
        transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping);
    }
}

修改后每次点击鼠标中键,autoRotate都会准确切换一次状态,首次点击就能正常生效。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:45:54