随机生成特定值的方法 Math.random 在 Corona SDK 中使用。

我有一组预先声明的值来设置对象的特定旋转角度。

local rotations = {900,-900}

我希望我的块生成函数能够随机从此函数中选择其中之一:

local blocks = {}
timerSrc = timer.performWithDelay(1200, createBlock, -1)

function createBlock(event)
   b = display.newImageRect("images/block8.png", 20, 150)
   b.x = 500
   b.y = math.random(100,250)
   b.name = 'block'
   physics.addBody(b, "static")
   transition.to( b, { rotation = math.random(rotations), time = math.random(2700,3700)} )
   blocks:insert(b)
end

当我使用:

 rotation = math.random(-900,900)

它只选择在两个数字之间的任何值而不是其中之一。我该怎么正确做?

点赞
用户1009479
用户1009479

如果m是一个整数,math.random(m)将随机返回区间[1,m]内的整数。因此,math.random(2)将随机返回整数1或者2

要生成随机数900-900,请使用:

rotation = math.random(2) == 1 and 900 or -900
2014-05-07 12:03:03