-1

I use common functions like map() and clamp() to transform values. I wonder if there is a similar mathematical function which lets me translate a rising value to an on and off state (0 and 1). Could a square wave help?

For more context: I want the value to be 1 whilst something is animating and 0 after it finished. The input value is clamped, the functionality of the function I'm looking for is like a switch. It would be a substitute for a complex if statement. Executed in a loop I'm trying to save resources by not using performance heavy if statements.

Looking forward to your input!

sketch

Sebe
  • 51
  • 4
  • 2
    You mean a lookback ? If previous is lower set 1, otherwise set 0 ? – Cesare Polonara Apr 30 '22 at 22:27
  • "loopback" sounds like a good name for it! Unfortunately I couldn't find any further information on this keyword. @CesarePolonara – Sebe Apr 30 '22 at 22:41
  • Is there a reason you can't simply use `if (value > 0 && value < 1)`? It is an if statement, but it's one that plays well with [branch prediction](https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array/11227902#11227902) and the condition it checks is very fast, so I would expect it to run once per frame just fine. If this works for you, great! If it doesn't, understanding why not will help me understand what it is exactly that you're looking for. – Kevin Apr 30 '22 at 22:48
  • It would help if you tell us what are you using to perform the animation. – Cesare Polonara May 01 '22 at 04:09

1 Answers1

0

This is what I came up with in the end. Not sure if this is helpful to anyone else. It converts any value between 0 and 1 to 1. But if the input value is equal to 0 or the input value is equal to 1, the function will return 0 as well.

Resulting in the loopback / switch behavior. It returns 1 only whilst a value is progressing. Hope this makes sense and is correct. Happy to hear your thoughts.

Also happy to hear some further thoughts on if such a function is more performant than an if-statement.

In the end I had to solve this to prove to myself that it's possible to do with math. (of course it is):)

const loopback = (i, m = 100) => {
    //returns 1 while value is progressing, returns 0 if value is 0 or 1
    //based on triangle wave function: https://discourse.processing.org/t/sawtooth-wave-algorithm/27433
    i = clamp(i) //normalize value to 0-1
    return Math.ceil(Math.abs((i*(m)) % (m)) / m)
}


const clamp = (number, min = 0, max = 1) => {
    return Math.max(min, Math.min(number, max));
}

//in my usecase, this is an alternative to following condition:
/*if(i >= 1 || i <= 0) {
  return 0;
} else {
  return 1;
}
Sebe
  • 51
  • 4