I’m trying to write some code that will play a piece of music and animate some rectangles in time to the beat. The rectangles will “pulse”, i.e. grow bigger/smaller in time to the music. I’m using transitions to do that and they’re working fine.
However, I have 4 rows of rectangles and they each pulse at slightly different times, i.e. Row 1 pulses on the beat, Row 2 a quarter of beat later and so on. I’m using a timer to call a function, onNextRow, every quarter beat - which for the purposes of this you can assume is 250 milliseconds - and that function sets off the transitions for that row. So, every 4 rows is one beat, and once the 4th row has been animated, I start again with Row 1.
Is this the best way to achieve this? Whilst I have the code up and running, I am finding that after a few seconds the timer starts to drift out of sync with the music. The transitions appear to be taking the correct amount of time, but they seem to be starting later and later due to the timer.
For example, onNextRow should be called every 250 milliseconds but the first call is at, effectively, 0 milliseconds, i.e. when the music starts. Given those figures, I should be seeing onNextRow called at the following intervals; Row 1 = 0 ms, Row 2 = 250 ms, Row 3 = 500 ms, Row 4 = 750 ms, Row 5 (which is effectively beat 2) = 1000 ms and so on.
What I’m experiencing via Print statements to output elapsed time, is that these times are drifting. So, whilst the first few rows are called as per the example above - give or take a millisecond here or there - the overall trend is upwards, i.e. by about the 8th row more than 2000 ms has passed by the time onNextRow is called. In effect, my boxes are now pulsing behind the beat.
A bit of sample code to help illustrate. This is deliberately simplified here. The full code “works”, i.e. the music plays and the boxes animate in time to the music. However, the timing starts to drift after a second or so and that’s my problem. The code below illustrates the basics of this.
local function onBoxTransitionComplete(box)
-- Code to do "stuff" once the Transition is complete
end
local function onNextRow()
-- Animate the current row
local box = display.newRect(100, 100, 100, 100)
transition.to(box, {time = 250, height = 200, width = 200, onComplete = onBoxTransitionComplete})
end
-- Call this timer/function immediately and only once
timer.performWithDelay(0, onNextRow, 1)
-- Call this timer/function every 250 ms and call indefinitely
timer.performWithDelay(250, onNextRow, 0)
Can anyone help me with this? [import]uid: 26769 topic_id: 6970 reply_id: 306970[/import]
