MentalCombination
MentalCombination

Reputation: 63

Random spawn location in Corona

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?

Upvotes: 1

Views: 56

Answers (1)

ldurniat
ldurniat

Reputation: 1702

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.

Upvotes: 1

Related Questions