In a C# Class need to filter out or ignore Boolean changes in an Update method if the interval between changes is too short.
In essence I need what is called a 'Low Pass Filter'
Lets say we have the following in either Update or FixedUpdate
if (myBoolean condition){
myVal =0;
}else{
myVal= _rawInput;
}
What is happening is myBoolean condition in the above is switching too rapidly. I need to 'filter out' or ignore these short intervals.
I've tried using this LowPass Filter class for use with mobile accelerometer input but without luck since it assumes the value being filtered is a float. http://devblog.aliasinggames.com/accelerometer-unity/ Can anyone help?
LowPassFilter?
using System;
using System.Linq;
public class Program
{
public static bool MyValue = false;
public static DateTime lastChange { get; set; } = DateTime.MinValue;
public static void ChangeValue(bool b)
{
// do nothing if not 2s passed since last trigger AND the value is different
// dont reset the timer if we would change it to the same value
if (DateTime.Now - lastChange < TimeSpan.FromSeconds(2) || MyValue == b)
return;
// change it and remember change time
lastChange = DateTime.Now;
MyValue = b;
Console.WriteLine($"Bool changed from {!b} to {b}. Time: {lastChange.ToLongTimeString()}");
}
public static void Main(string[] args)
{
for (int i = 0; i < 10000000; i++)
{
ChangeValue(!MyValue);
}
}
}
Output:
Bool changed from False to True. Time: 23:29:23
Bool changed from True to False. Time: 23:29:25
Bool changed from False to True. Time: 23:29:27
The whole loop runs for about 7s - thats about 1.15 million triggers per second to change it.