Mag*_*age 10 c# mobile accelerometer unity-game-engine
我会假设Unity有一些事件触发器,但我在Unity3d文档中找不到一个.我是否需要处理加速度计的变化?
谢谢你们.
Dan*_*ard 15
关于检测"抖动"的优秀讨论可以在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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我建议您阅读整个线程以获取完整的上下文.