[英]How can I detect a shake motion on a mobile device using Unity3D? C#
我會假設Unity有一些事件觸發器,但我在Unity3d文檔中找不到一個。 我是否需要處理加速度計的變化?
謝謝你們。
關於檢測“抖動”的優秀討論可以在Unity論壇的這個主題中找到。
來自Brady的帖子:
從我在一些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);
}
}
注意:我建議您閱讀整個線程以獲取完整的上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.