我会假设Unity有一些事件触发器,但我无法在Unity3d文档中找到它。我是否需要处理加速度计的变化?
谢谢大家。
答案 0 :(得分:15)
关于检测“摇晃”的优秀讨论可以在Unity论坛的this thread中找到。
来自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);
}
}
注意:我建议您阅读完整上下文的整个帖子。