我在电晕中使用以下代码在随机位置创建随机图像 每次我运行我的代码,但当我运行代码时,我得到所有随机选择 屏幕上相同位置的图像
这是我的代码,请提出建议..提前谢谢
----在创建场景中,此代码为
letterHolder = {}
numOfImages = 10
for i=1,numOfImages do
letterHolder[i] = display.newImageRect("images/myImage.png", 20, 20)
letterHolder[i].x = math.random(0, display.contentWidth)
letterHolder[i].y = math.random(0, display.contentHeight)
end
答案 0 :(得分:0)
试试以下方法。这可能会对您有所帮助:
local letterHolder = {}
local numOfImages = 10
local xPosArray = {}
local yPosArray = {}
local randX,randY = 0,0
local xExists,yExists = 0,0
local function positionImages(i)
randX = math.random(display.contentWidth)
randY = math.random(display.contentHeight)
if(i==1)then
xPosArray[i] = randX
yPosArray[i] = randY
else
xExists = table.indexOf( xPosArray, randX )
yExists = table.indexOf( yPosArray, randY )
if(xExists~=nil and yExists~=nil and xExists==yExists)then
print("Place already occuped")
positionImages(i)
else
print("Can place here")
xPosArray[i] = randX
yPosArray[i] = randY
end
end
end
for i=1,numOfImages do
letterHolder[i] = display.newImageRect("images/myImage.png", 20, 20)
positionImages(i)
end