Log In  
Follow
peace

Hey everyone,

I wanted to share a standalone function I've been using in my recent PICO-8 projects called loopi (LoopIndex).

It's designed to loop an index across a specified range based on the elapsed time, making it really handy for animations or any time-sensitive indexing. The function also includes an optional 'invert' feature, which creates a smooth back-and-forth motion.

Here's the snippet (46 tokens):

function loopi(range, delay, invert)
    local idx = flr((time() / delay) % (invert and 2 * (range - 1) or range))
    if invert and idx >= range then
        idx = 2 * (range - 1) - idx
    end
    return idx    
end

Minified (42 tokens):

function loopi(r,d,i)local x=flr(time()/d)%(i and 2*(r-1)or r)return i and min(x,2*(r-1)-x)or x end

Note: If you don't want to tie the timings to the time() output, you can replace it with something else or by adding a new argument - Otherwise, it works nicely as a standalone function :)

Example Usage:

Let's say you want to cycle through sprites at positions 5 to 8 based on time. You can use loopi to calculate the appropriate sprite index:

function _update()
    -- Loop through sprite indexes 5 to 8 every 0.5 seconds without inversion
    sprite_index = 5 + loopi(4, 0.5, false)
end

This setup will continuously loop the sprite index from 5 to 8, changing every 0.5 seconds. If you want the sprites to animate forward and then backward (like a ping-pong effect), just set the invert parameter to true.

Demo:

[ Continue Reading.. ]

2
0 comments