user16999379
user16999379

Reputation:

How to generate a random decimal number in love2D?

I tried generating a random decimal number between (lets say between 0.3 and 0.8) in love2d using the following code:

x=math.random(0.3, 0.8)
print(x)

but what happens is it generates 0.3 every single time I run the program and the 0 in 0.4 kind of flickers (in the sense like it changes to 1).

If it helps, here's a screen record of what happens https://vimeo.com/632949687

Upvotes: 1

Views: 386

Answers (3)

koyaanisqatsi
koyaanisqatsi

Reputation: 2813

In LÖVE there is a platform independent version of random() present.
https://love2d.org/wiki/love.math.random
With no need to use of math.randomseed() or love.math.setRandomSeed().
For float numbers in the range 0 and 1 simply use...
love.math.random()

'but what happens is it generates 0.3 every single time'
Same here, so the simpliest way seems to be @lhf' example.

Upvotes: 1

lhf
lhf

Reputation: 72352

Your problem is underspecified. Here are two simple solutions; they're not equivalent.

This generates random numbers in the set {0.3,0.4,0.5,0.6,0.7,0.8}:

math.random(3,8)/10

This generates random numbers in the interval [0.3,0.8):

0.3+(0.8-0.3)*math.random()

Upvotes: 2

Youness Dominique
Youness Dominique

Reputation: 17

check the function

function random(min, max, precision)
    local precision = precision or 0
    local num = math.random()
    local range = math.abs(max - min)
    local offset = range * num
    local randomnum = min + offset
    return math.floor(randomnum * math.pow(10, precision) + 0.5) / math.pow(10, precision)
end

Upvotes: -1

Related Questions