Codesnippets > Math

Small calc optimizations

(1/4) > >>

tictac:
Hello, I'm new in GLBasic, and this is my first official post!  :booze:

I wish to give my contribute in calculation optimization (tricks!).

1) I noticed that many people, to get a sprite rotating (forever!), they use something like this:

--- Code: (glbasic) ---counter = 0
while true
inc counter, 1
if counter >= 360 then counter = 0
wend

--- End code ---

Even if it is correct, using an if is usually a "slow" procedure. Istead, you can use this code:

--- Code: (glbasic) ---counter = 0

WHILE TRUE
INC counter, 1

PRINT MOD(counter, 360), 100, 100

SHOWSCREEN
WEND

--- End code ---

In this way, the "mod" makes the "dirty" job, and it is faster than using "if".

Another trick is about values switching:

1) true -> false -> true ....
2) 1 -> 0 -> 1 -> ......

You can use the following code:

BOOLEAN:

--- Code: (glbasic) ---boolValue = FALSE

WHILE TRUE
boolValue = bNOT(boolValue)
PRINT boolValue, 100, 100

SHOWSCREEN
WEND

--- End code ---

FOR "1" AND "0" ......

--- Code: (glbasic) ---boolValue = 0

WHILE TRUE
boolValue = 1 - boolValue
PRINT boolValue, 100, 100

SHOWSCREEN
WEND

--- End code ---

In order to see the result, you can put, in the first line, an FPS limiter:

--- Quote ---limitfps 3 ; 3 frames per second.

--- End quote ---

I hope this small tutorial will help some people! (my 0.02\$ contribution!)

Kitty Hello:
another trick is to ignore all this and do:

--- Code: (glbasic) ---ROTOSPRITE 0,x,y, 12312341.5

--- End code ---
it's wrapped automatically. No problem for the ROTO... functions as well as SIN/COS. Only, if you want to "display" the angle, it's better to use the fmod command.

PeeJay:
while this is marginally faster, the problem comes when counter reaches really high numbers, as there must be an upper limit that GL can count up to .....

Moru:
This is one of the things that make realy old games mysteriously crash after a certain time :-)

tictac:
Yes, I think automatic wrapping (for the functions) is a good feature, but a real programmer must take full control of its application.
Thank you because I discovered even fmod and not only mod  :booze: