Rolling Clamp (numbers looping in a range)

1

Stats

2,089 visits, 2,779 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 1 Oct, 2014. Last updated 19 Feb, 2019

If you're ever in a situation where you need to be able to shift through a range of numbers, you may find yourself wanting to "roll" or "loop" through those numbers. You're possibly simulating the animation of a sprite in a controlled fashion. Perhaps you've got a level editor and you're setting the selected tile type by scrolling the mouse wheel. Maybe you've even drummed up some awesome AT-based combat system for your smokin' new RPG.

This is pretty convoluted to do with a simple expression, but if you're anything like me, you enjoy the elegance of a one-liner and appreciate a little mathematical pixie dust just as much as the next guy. Well, I may have a quick and dirty solution for you; enter the "rolling clamp". ;)

    abs(-TOTAL - (CURRENT + DIRECTION)) % TOTAL

Personally, I would suggest to simply use it in an expression as a function (outside of a plugin) is a bit cumbersome to work with.

Here is an example of doing this in that tile type selection I mentioned earlier:

So there it is. It's nothing huge, major, or grand, but it's a cute little trick that I thought might help someone out some day, so here it is.

Edit: I forgot to mention that if your range is not 0-bound (e.g. 0~9 as opposed to 1~10 or 10~20), then you'll need to add the offset at the beginning (or end) of the expression as such:

    OFFSET + (abs(-TOTAL - (CURRENT + DIRECTION)) % TOTAL)

OFFSET in the cases referenced above would be 1 and 10 respectively.

  • 0 Comments

Want to leave a comment? Login or Register an account!