- Home /
How can I detect when a float value crosses an integer threshold?
I have a float value that I'm trying to have trigger a sound event whenever it crosses past an integer threshold. The user is able to increment the value in 0.1 increments.
In other words, whenever the value equals the nearest integer, I want to play a sound... so when the user takes it from 3.1 to 3.0, BING. and when they take it from -1.9 to -2.0, BING! and when they take it from 0.9 to 1.0, BOP!, and when they take it from -4.1 to -4.0, BOP! It seems that somehow my internal math manipulations are also slipping float values from time to time, transforming 3.1 into 3.0999999, so a solution adjusting for that strange variance would also be greatly appreciated.
Here's the code that works 30% of the time:
var g_MC = new Vector4[n];
function chargeDown(h) {
g_MC[h].w -= 0.1;
if (Mathf.Abs(g_MC[h].w) - Mathf.Round(Mathf.Abs(g_MC[h].w)) < 0.01) {
AudioSource.PlayClipAtPoint(g_sFXchargeDown, Vector3(g_MC[h].x, g_MC[h].y, g_MC[h].z));
Debug.Log("CHARGE DOWN ---- BING!");
}
}
function chargeUp(h) {
g_MC[h].w += 0.1;
if (Mathf.Abs(g_MC[h].w) - Mathf.Round(Mathf.Abs(g_MC[h].w)) < 0.01) {
AudioSource.PlayClipAtPoint(g_sFXchargeUp, Vector3(g_MC[h].x, g_MC[h].y, g_MC[h].z));
Debug.Log("CHARGE UP ---- BOP!");
}
}
Answer by Owen-Reynolds · Dec 10, 2014 at 06:16 AM
Standard trick is to use a "trailer." In your case, just always remember the previous int value. Whenever it changes, fire and update.
As cdrann points out, negative numbers round funny, so add 1000 (whatever the lowest negative value is. Can also check for negative and round differently, but "make it positive" is easier):
float oldIntVal = (int)(val+1000);
...
float newIntVal= (int)(val+1000);
if(newIntVal!=oldIntVal) { playSound(); oldIntVal=newIntVal; }
very elegant. and lightweight on the processor. thank you Owen.
Answer by cdrandin · Dec 10, 2014 at 02:17 AM
One way to determine int threshold you are talking about would be to use modulo as follows:
1.0%1.0 = 0
1.1%1.0 = 0.1
...
1.n%1.0 = 0.n
2.0%1.0 = 0
For negative take into account and make sure to make it positive. Modulo works in the positive range. I believe this modulo works in C#