简体   繁体   中英

random images in corona sdk

I have 3 images and 1 button -

I want to be able to click my button and have 1 of the 3 images appear. And everytime I click the button i want a new random image to appear in the place of the last image......Pretty simple it would seem, but Im losing hair over this and am about to call it quits......Can anyone help me do this? I want to learn, so please comment the code if you decide to help me....Thanks in advance.

So far, I have:

display.setStatusBar( display.HiddenStatusBar ) -- hide status bar

--insert background
local bgImg = display.newImageRect( "images/myBG.jpg", 625, 450 ) 
bgImg.x = display.contentCenterX -- center bg on X
bgImg.y = display.contentCenterY -- center bg on Y

-- scripture references
myTable = {
  display.newImage("images/btnLogo1.png"), 
  display.newImage("images/btnLogo2.png"),
  display.newImage("images/btnLogo3.png"),
}

randomPicture = myTable[math.random(1,3)]

This should work:

-- scripture references
myTable = {
"images/btnLogo1.png",
"images/btnLogo2.png",
"images/btnLogo3.png",
}

local randomPicture = myTable[math.random(1,3)]
display.newImage(myTable[randomPicture])

I hope you need no explanation about it :)

If your image names are continous, that is like img_1 , img_2 , img_3 . etc... then you can use the following method:

-- Display an image
local myImage = display.newImageRect("images/btnLogo1.png",50,50)
myImage.x = display.contentWidth/2
myImage.y = display.contentHeight/2

-- Call this function on button click
function imageChangeFunction()
  -- remove the previous image 
  if(myImage)then myImage:removeSelf() end
  -- creating the sprite with new image
  myImage = display.newImageRect("images/btnLogo"..math.random(3)..".png",50,50)
  myImage.x = display.contentWidth/2
  myImage.y = display.contentHeight/2
  print("Image changed...")
end
-- Here I am assigning the listener to Runtime, you can change it for your button
Runtime:addEventListener("tap",imageChangeFunction) 

Note:
math.random(3) gives you any random number between 1 and 3.
.. is used for concatenation. So, "images/btnLogo"..math.random(3)..".png" will give you any of the following strings:

  images/btnLogo1.png
  images/btnLogo2.png
  images/btnLogo3.png

For more info, visit: math.random() and Corona String Operations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM