0

每次运行代码时,我都在电晕中使用以下代码在随机位置创建随机图像,但是当我运行代码时,我会在屏幕上的同一位置获得所有随机选择的图像

这是我的代码,请提供建议..提前谢谢

----在创建场景中这段代码是放置的

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
4

1 回答 1

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
于 2013-07-15T12:28:07.903 回答