2013-07-10 25 views
0

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

这里是我的代码,请大家给建议..谢谢提前

----在创建场景此代码是地方

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 
+3

我试过你的代码,它似乎确定,他们随机在不同的位置,你可以指定你的问题更多? – NaviRamyle

+2

这是你粘贴的整个代码吗?当我搞乱随机种子时,我遇到了类似的问题。随机种子的问题是,对于相同的种子,您将获得相同的一组随机数。无论如何..如果这是整个事情尝试在for循环之前添加math.randomseed(os.time())。确保您不会每秒更多次地调用此代码! – Krystian

回答

0

刚刚尝试以下会见HOD。这可能会帮助你:

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