How to create objects at random positions?

Here is a function that I made, it spawns an object at a fixed location, but I want it to spawn randomly inside the phone screen (which is 1080x1920).

-- BALLOON SPAWN FUNCTION function spawnBalloon( event ) balloon = display.newImage("balloon1.png") balloon.x = display.contentCenterX balloon.y = display.contentCenterY balloon:addEventListener("tap", spawnBalloon) balloon:addEventListener("tap", removeBalloon) end

How can I do that?

https://docs.coronalabs.com/api/

  1. Determine the bounds of the screen using the related display.* properties: https://docs.coronalabs.com/api/library/display/index.html#properties
  2. Knowing those bounds and the size of your objects, use math.random() to select the x and y.

This is similar, but not the same and checks for overlap to avoid that:

https://github.com/roaminggamer/RG_FreeStuff/raw/master/AskEd/2015/07/overlapTest.zip

https://www.youtube.com/watch?v=K3ixlmzfgNk

If you’re making a balloon popper as a starting point or for learning, I have one on the marketplace:

Lastly, be sure to check out:

Try

local \_T = display.screenOriginY local \_B = display.viewableContentHeight - display.screenOriginY local \_L = display.screenOriginX local \_R = display.viewableContentWidth - display.screenOriginX local mRandom = math.random ... balloon.x = mRandom( \_L, \_R ) balloon.y = mRandom( \_T, \_B )

Center of object remains on the screen.

Thank you both Idurniat and roaminggamer! 

https://docs.coronalabs.com/api/

  1. Determine the bounds of the screen using the related display.* properties: https://docs.coronalabs.com/api/library/display/index.html#properties
  2. Knowing those bounds and the size of your objects, use math.random() to select the x and y.

This is similar, but not the same and checks for overlap to avoid that:

https://github.com/roaminggamer/RG_FreeStuff/raw/master/AskEd/2015/07/overlapTest.zip

https://www.youtube.com/watch?v=K3ixlmzfgNk

If you’re making a balloon popper as a starting point or for learning, I have one on the marketplace:

Lastly, be sure to check out:

Try

local \_T = display.screenOriginY local \_B = display.viewableContentHeight - display.screenOriginY local \_L = display.screenOriginX local \_R = display.viewableContentWidth - display.screenOriginX local mRandom = math.random ... balloon.x = mRandom( \_L, \_R ) balloon.y = mRandom( \_T, \_B )

Center of object remains on the screen.

Thank you both Idurniat and roaminggamer!