dk3611
dk3611

Reputation: 51

Creating random images at random position in corona sdk

I am using the following code in corona to create a random images at random position each time i run my code, but when i run the code i get all the random selected images on the same position on the screen

Here is my code please give suggestion.. thanks in advance

---- in the create scene this code is places

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

Upvotes: 0

Views: 2038

Answers (1)

Krishna Raj Salim
Krishna Raj Salim

Reputation: 7390

Just try the following method. This may help you:

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

Upvotes: 0

Related Questions