如何使用Unity3D检测移动设备上的震动运动?c#



我本以为unity对此有一些事件触发器,但我在Unity3d文档中找不到。我需要在加速度计的变化?

关于检测"震动"的优秀讨论可以在Unity论坛的这个帖子中找到。

选自Brady的帖子:

我能告诉你的是在一些苹果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);
    }
}

注意:我建议你阅读整个线程的完整背景。

最新更新