Shaking an object?

Pretty simple; I have a display object I need to visually / violently shake on-screen for a small length of time. The easiest thing that comes to mind is a recursively timed function, that is...

1
2
3
4
5
6
7
8
9
10
11
local time = 1
local object = display.newRect(0, 0, 100, 100)
 
local shakeThis = function()
  if time < 500 then
     local shakeX, shakeY = math.random(5), math.random(5) -- generate random delta
     object:translate( shakeX, shakeY) -- move to delta
     time = time + 1 -- increment counter
     timer.performWithDelay(50, shakeThis) -- perform again in 50ms
   end
end

well, you have to start the loop ;)

1
2
3
4
5
6
7
8
9
10
local time = 1
local function shakeThis()
  if time < 500 then
     print ("beep")
     time = time + 1 -- increment counter
     timer.performWithDelay(50, shakeThis) -- perform again in 50ms
   end
end
 
shakeThis() ------- let's go!

Of course you do. :) But if you read carefully, I do manage to trigger the function. It's just that despite the function starting, I can't get it to do what it seemingly should be capable of.

Using 'if', the function seems to quit out before the timer can perform.

Using 'while' the function will print as many statements as I like but the display object only moves once. (It's either only moving the first time or maybe only doing a single update once all of the translates are performed?)

ah I see, it's a scope problem:

1
2
3
4
5
local shakeThis = function()
     print ("beep!")
     shakeThis()  -- not in scope of this function
end
shakeThis() -- beep!

I have no idea why the table version works. But it does seem to do so. Cool!

Have you tried :

1
2
3
4
5
6
local shakeThis
shakeThis =  function()
     print ("beep!")
     shakeThis()
end
shakeThis() -- beep!

@richard9, from what I see with the translate, you object will only move in one direction, not really shake, unless that is the effect you want and are referring to as shake.

your x, y are between 1 and 5 and each time you translate, they get added in the Bottom Right direction only.

Yeah, JayantV - I noticed as much when I tried the table function. Shouldn't be too hard to solve though, I just need to apply a constant to the random output (eg: if I want -5 to + 5 I can just use math.random(11) and then use result = result - 6 to get the correct value range.) :-)

MrMells...well, that looks comprehensive. I'll sit down and try to understand it in the morning.

views:2317 update:2012/2/12 11:34:30
corona forums © 2003-2011