Function to create a "stepped," diagonal line

532 Views Asked by At

First off, sorry if this is a basic question or one that has been asked before. I really don't know how to phrase it, so it's a hard question to google.

I'm looking for a function that will generate a line similar to the one below

       __/
    __/
 __/
/

I'm pretty good at math, but for some reason this seems to be stumping me as it seems like it should be really simple.

In case it helps, I am planning on using it to drive an animation, so that it moves, pauses, moves, pauses, etc. using the current time (zero through infinity) as the input.

I am using an "Absolute," system (IE: if I were to jump to frame 35, the math needs to be able to calculate frame 35 without knowing the frames before it), so I can't do anything like if (floor(sin(time)) + 1 > 0) { add 1 }

2

There are 2 best solutions below

0
On BEST ANSWER

John Wayland's answer was good, and worked on the project I needed, but after playing around on a different project I came up with a more "tweakable," function that does the same thing, but allows changing of parameters.

D is the duration of one cycle, T is the amount of time the transition should take, and A is the amount of change between cycles.

$$cycle(x) = A(max\{\frac{(x \mod D) -D}{T} + 1, 0\} + \lfloor \frac{x}{D} \rfloor)$$

Breakdown

Create saw wave with intended duration $$(x \mod D)$$ clamp it so that only 1 unit is greater than 0 $$max\{(x \mod D) - D + 1, 0\}$$ set duration of transition $$max\{\frac{(x \mod D) -D}{T} + 1, 0\}$$ create stepped line, where each step is the duration of one cycle $$\lfloor\frac{x}{D}\rfloor$$ Add the two together so that each step of the previous functions "lifts," each cycle up by 1 unit $$max\{\frac{(x \mod D) -D}{T} + 1, 0\} + \lfloor \frac{x}{D} \rfloor$$ Finally multiply the whole thing by A to set the amount of desired change between cycles.

Screenshot of working function

As a bonus, you can also wrap the max function in a smoothstep function and get a very nice smooth graph for animation

$$S(x)=x^2(3-2x)$$ $$cycle(x) = A(S(max\{\frac{(x \mod D) -D}{T} + 1, 0\}) + \lfloor \frac{x}{D} \rfloor)$$

Screenshot of working smoothsetpped function

2
On

Here is one example:

$$ f(x)=\left\vert \frac{x-1}{2}-\left\lfloor\frac{x}{2}\right\rfloor\right\vert+\frac{x-1}{2}$$

stair-step