Topic was automatically imported from the old Question2Answer platform.
Asked By
Newby
I am randomizing my enemy hp and speed for more variation so i made a script to get their random values with a min and max amount. It is a bit long for what it is supposed to do.
func _ready():
randomize()
var hp = randi() % MAX_HP + 1
var speed = randi() % MAX_SPEED + 1
if hp < MIN_HP:
hp += MIN_HP
if speed < MIN_SPEED:
speed += MIN_SPEED
HP = hp
MAX_SPEED = speed
Is their a better method in choosing a random number between a min and max amount
# random number between MIN and MAX:
var n = randi() % (MAX - MIN) + MIN
Alternatively, you can use the randi_range() function provided by RandomNumberGenerator:
var random = RandomNumberGenerator.new()
func _ready():
random.randomize()
var n = random.randi_range(MIN, MAX)
Performance wise which one would be better?
Newby | 2020-02-12 02:01
That’s not even worth asking. Performance is not something to worry about - just write your code. Worry about performance when you actually encounter something that impacts performance, if you ever do. And if you do, your random number code is not going to be it.
kidscancode | 2020-02-12 02:54
Actually it should be modulo (MAX - MIN + 1). Otherwise you never will get MAX as a result. RandomGenerator does the same thing. As this is currently selected as best answer, you should consider editing it. Also note that this method tends to be biased.