[Gambas-user] "wrapping" function based on recent Mod thread

Kevin Fishburne kevinfishburne at ...1887...
Sun Oct 6 05:40:08 CEST 2013


Jesus Guardon said in the recent thread "Modulo operator returns wrong 
results ":

    Hi Paul et all

    When working with some video games, there are a feature called
    wraparound or screen wrap. It consists on objects leaving one side of
    the screen that immediately reappear on the opposite side, maintaining
    speed and trajectory. For this task usually modular arithmetic is used,
    involving the Mod operator.

    As I said before, on Python at least, it works as expected with
    negative
    numbers, and not only integers.

    Lets imagine a spaceship in a drawing area 800px wide that reaches past
    the left edge of the screen. Just before it passes, say at pixel 2 in X
    coordinates, the operation would be:

    2 Mod 800 = 2

    So, nothing has changed in its position. But when the ship is at
    negative coordinates, say again -2:

    -2 Mod 800 = 798

    That's exactly the opposite side of the drawing area, which is what I
    had expected. If -2 would be returned instead, it won't work.

    However this is not an issue for me, since this can be solved this way:

    Private Sub fmod(Dd As Float, d As Float) As Float

          If Dd < 0 Then
              Return Abs((Frac(Dd / d)) * d - d)
          Else
              Return (Frac(Dd / d)) * d
          Endif

    End

    So no need to modify gambas at all, ;-)

---

A couple of questions. First which is the upper-bound (screen 
width/height) and which is the current value (position), Dd or d? 
Second, is there a way using this algorithm to specify the lower-bound? 
The solutions I've found online for "wrapping" a number between an 
arbitrary lower- and upper-bound don't work when the value being wrapped 
is negative. The algorithm I'm using is horribly inefficient, as it uses 
loops.

-- 
Kevin Fishburne
Eight Virtues
www: http://sales.eightvirtues.com
e-mail: sales at ...1887...
phone: (770) 853-6271





More information about the User mailing list