讀加速計感測器(高階)
直接使用來自加速計感測器的原始值來移動或旋轉 GameObject 會導致諸如抖動或振動等問題。建議在使用前平滑值。事實上,加速計感測器的值應始終在使用前平滑。這可以通過低通濾波器實現,這就是 Vector3.Lerp
到位的地方。
//The lower this value, the less smooth the value is and faster Accel is updated. 30 seems fine for this
const float updateSpeed = 30.0f;
float AccelerometerUpdateInterval = 1.0f / updateSpeed;
float LowPassKernelWidthInSeconds = 1.0f;
float LowPassFilterFactor = 0;
Vector3 lowPassValue = Vector3.zero;
void Start()
{
//Filter Accelerometer
LowPassFilterFactor = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds;
lowPassValue = Input.acceleration;
}
void Update()
{
//Get Raw Accelerometer values (pass in false to get raw Accelerometer values)
Vector3 rawAccelValue = filterAccelValue(false);
Debug.Log("RAW X: " + rawAccelValue.x + " Y: " + rawAccelValue.y + " Z: " + rawAccelValue.z);
//Get smoothed Accelerometer values (pass in true to get Filtered Accelerometer values)
Vector3 filteredAccelValue = filterAccelValue(true);
Debug.Log("FILTERED X: " + filteredAccelValue.x + " Y: " + filteredAccelValue.y + " Z: " + filteredAccelValue.z);
}
//Filter Accelerometer
Vector3 filterAccelValue(bool smooth)
{
if (smooth)
lowPassValue = Vector3.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
else
lowPassValue = Input.acceleration;
return lowPassValue;
}