# Random timer (another random question)

Hi all!

I’m messing around trying to make a timer that spawns objects at .25 second, .5 second, and 1 second intervals randomly.

I’m lost though…

What I have so far is below but not sure where to go from there.

``````
function setup()

timer=0

time={}

timerFreq={.25,.5,1}

end

function draw()

timer = timer + DeltaTime

for a,b in ipairs(timerFreq) do
local random=math.random(1,3)
table.insert(time,timerFreq[random])
if timer > time then
spawnObject()
end
end

end

``````

As you can see I’m totally mixed up with this timer, not really sure how to put it all together.

Any tips would be greatly appreciated!

``````-- Random Spawn

-- Use this function to perform your initial setup
function setup()
timerFreq={0.25,0.5,1}
nextRespawn=timerFreq[math.random(3)]
counter=0
end

-- This function gets called once every frame
function draw()
counter = counter + DeltaTime
if counter>nextRespawn then
print("respawn at "..counter)
counter=0
nextRespawn=timerFreq[math.random(3)]
end
end

``````

@Crumble Try this.

``````
function setup()
start=true
end

function draw()
background(40, 40, 50)
if start then
startTween()
end
end

function startTween()
local timerFreq={.25,.5,1}
start=false
local delay=timerFreq[math.random(3)]
print("delaying",delay)
t1=tween.delay(delay,function() start=true end)
end

``````

@Crumble Or this.

``````
function setup()
startTween()
end

function draw()
background(40, 40, 50)
end

function startTween()
local timerFreq={.25,.5,1}
local delay=timerFreq[math.random(3)]
print("delaying",delay)
t1=tween.delay(delay,function() startTween() end)
end

``````

is this timer accurate?compared to the use of tween.delay?0, callback??

I’ll try these when I get home, thanks guys!

Those work great! It’s cool to see the different ways that it can be done, would have never thought to use Tweens.

Kind of along the same lines, but how would when tapping the screen, make Codea play random sounds from a table?

I tried:

``````
function setup()

soundsTable={sound("A Hero's Quest:Bottle Break 1"),sound("A Hero's Quest:Arrow Shoot 1")}

soundPlayed=soundsTable[math.random(2)]

end

function touched(t)

if t.state==BEGAN then
if t.x > 0 and t.x < WIDTH and t.y > 0 and t.y < HEIGHT then
sound(soundPlayed)
end
end
end

function draw()

background(0)

end

``````

but it plays a sound when program starts then I’m getting an error when touching the screen saying “codeasoundbuffer expected, got user data”… I need to wrap my head around how to use the random function with tables…

Any tips?

Edit: never mind I figured it out, was a dumb mistake, I was using sound() in the table instead of just using the file name… so Codea was trying to run sound(sound(file name))