【问题标题】:How can I detect a shake motion on a mobile device using Unity3D? C#如何使用 Unity3D 检测移动设备上的抖动运动? C#
【发布时间】:2015-07-13 17:20:10
【问题描述】:

我会假设 unity 对此有一些事件触发器,但我在 Unity3d 文档中找不到。我需要处理加速度计的变化吗?

谢谢大家。

【问题讨论】:

    标签: c# mobile unity3d accelerometer


    【解决方案1】:

    可以在 Unity 论坛上的 this thread 中找到有关检测“抖动”的精彩讨论。

    来自布雷迪的帖子:

    从我在一些 Apple iPhone 示例应用程序中可以看出,您基本上只需设置一个矢量幅度阈值,在加速度计值上设置一个高通滤波器,然后如果该加速度矢量的幅度比您的设置阈值,它被认为是“摇”。

    jmpp 的建议代码(为了可读性和更接近有效的 C# 进行了修改):

    float accelerometerUpdateInterval = 1.0f / 60.0f;
    // The greater the value of LowPassKernelWidthInSeconds, the slower the
    // filtered value will converge towards current input sample (and vice versa).
    float lowPassKernelWidthInSeconds = 1.0f;
    // This next parameter is initialized to 2.0 per Apple's recommendation,
    // or at least according to Brady! ;)
    float shakeDetectionThreshold = 2.0f;
    
    float lowPassFilterFactor;
    Vector3 lowPassValue;
    
    void Start()
    {
        lowPassFilterFactor = accelerometerUpdateInterval / lowPassKernelWidthInSeconds;
        shakeDetectionThreshold *= shakeDetectionThreshold;
        lowPassValue = Input.acceleration;
    }
    
    void Update()
    {
        Vector3 acceleration = Input.acceleration;
        lowPassValue = Vector3.Lerp(lowPassValue, acceleration, lowPassFilterFactor);
        Vector3 deltaAcceleration = acceleration - lowPassValue;
    
        if (deltaAcceleration.sqrMagnitude >= shakeDetectionThreshold)
        {
            // Perform your "shaking actions" here. If necessary, add suitable
            // guards in the if check above to avoid redundant handling during
            // the same shake (e.g. a minimum refractory period).
            Debug.Log("Shake event detected at time "+Time.time);
        }
    }
    

    注意:我建议您阅读整个线程以了解完整的上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 2020-05-30
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多