Some handy functions

Started by VectorWorlds, January 26, 2020, 09:15:38 AM

Previous topic - Next topic

VectorWorlds

Hello,

I've written some very simple functions I needed for my game, but was wondering if they would make sense adding to the core GSBasic language.


Function Wrap(num,maxnum) 'Wraps a number e.g. providing an angle greater than 360 would wrap around to angle between 0 and 360
Return num Mod maxnum 'Example Wrap(405,360) would return 45
EndFunction

Function Sgn(innumber) 'Returns the sign of a number e.g. Sgn(-20.32) would return -1
If innumber < 0 Then
Return -1
Else
If innumber = 0 Then
Return 0
Else
Return 1
Endif
Endif
Endfunction

Function Rnd(maxamount) 'Return a random number between 0 and max amount
Return Rand() Mod maxamount
EndFunction

Function RndRange(_min,_max) 'Return a random number between _min and _max amount
spread=_max - _min
result = _min + (Rand() Mod spread)
Return result
EndFunction

function Clamp(_num,_minimum,_maximum) 'Keeps a number within a given range
if _num < _minimum then
return _minimum
else
if _num > _maximum then
return _maximum
else
return _num
endif
endif
EndFunction

Function DegToRad(radians)                           'Converts Degrees to Radians
Return radians * 0.0174533
EndFunction

Function RadToDeg(deg)                                'Converts Radians to Degrees
Return deg / 0.0174533
EndFunction

Function dCos(degrees)                                  'Cos using degrees as an input
Return cos(DegToRad(degrees))
EndFunction

Function dSin(degrees)                                   'Sin using degrees as an input
Return sin(DegToRad(degrees))
EndFunction


Might be nice to have Tan, Atan, and Atan2 function accepting degrees as well if possible?
I personally find degrees easier to visualise than radians so for my simple brain.

Cheers,


Andrew

Vectrex32

Thanks for the suggestions. I'm curious: why is Wrap() better than just the MOD operator?

- Bob

VectorWorlds

Hi Bob,

You're right.  There Wrap isn't any better than just using mod.  The only reason I use it to make my code more readable.  Functionally they do exactly the same thing, so its not issue if it's not added :)

Cheers,


Andrew