Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

How to create objects at random positions?
Started by amar.masic6 May 12 2018 08:48 AM

4 replies to this topic
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

amar.masic6

[GLOBAL: userInfoPane.html]
amar.masic6
  • Observer

  • 6 posts
  • Corona SDK

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?



[TOPIC: post.html]
#2

roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
  • Corona Geek

  • 6,920 posts
  • Corona SDK

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

 



[TOPIC: post.html]
#3

roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
  • Corona Geek

  • 6,920 posts
  • Corona SDK

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:


Edited by roaminggamer, 12 May 2018 - 09:06 AM.


[TOPIC: post.html]
#4

ldurniat

[GLOBAL: userInfoPane.html]
ldurniat
  • Contributor

  • 353 posts
  • Corona SDK

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.

  • roaminggamer likes this

[TOPIC: post.html]
#5

amar.masic6

[GLOBAL: userInfoPane.html]
amar.masic6
  • Observer

  • 6 posts
  • Corona SDK

Thank you both Idurniat and roaminggamer! 




[topic_controls]
[/topic_controls]