Corona SDK and other Game Development Tutorials
@gamebuilding

Using the shake event with Corona SDK

Hello, today I want to show how to use the shake event with Corona SDK. The Corona SDK platform allows you to detect when a user shakes his or her phone. This is great if you have a game, such as a magic 8 ball game, where you need to do something on a shake event.

So, here’s the code to detect a shake event.

-- Create a function to be called when the phone or mobile device is shaken
local function onShake (event)
    if event.isShake then
        -- Device was shaken, so do something.
    end
end
-- Create a runtime listener for the shake event
Runtime:addEventListener("accelerometer", onShake)

In the code above, we create a Runtime Listener to detect when the user shakes the phone. But, what good is this code if we don’t do something with it? Next, I want to show you how to change the background color using the shake event.

-- Create a background image that takes up the entire screen
background = display.newRect(0,0,display.contentWidth,display.contentHeight )
background:setFillColor( 255, 255, 255)

-- Create a function that changes the background color
function changeBackgroundColor()
    background:setFillColor(math.random(1,255),math.random(1,255),math.random(1,255))
end

-- Create a function to be called when the phone or mobile device is shaken
local function onShake (event)
    if event.isShake then
        -- Device was shaken, so change background
        changeBackgroundColor()
    end
end
-- Create a runtime listener for the shake event
Runtime:addEventListener("accelerometer", onShake)

In the above code, we made a few additions. First, we added a background, created a function that assigns a random color to the background when called and finally the function changeBackgroundColor is only called when the device is shaken. It’s that easy. Feel free to use my code in any of your upcoming projects and if you do, I’d love to hear about them.

If you would like to see more Corona SDK Tutorials please leave a comment, follow me on Twitter or purchase one of my apps. Thanks for reading!

9 Comments
  1. Thanks!

  2. hii… not working on gTab 2.0 ….
    help me

  3. Thanks for the nice tutorials!!

  4. Hi nice tutorial.

    I have question
    How do i make object go left-right-left…. when shake

    Thanks.

    • You would probably have to move the object along the x axis. Something like object.x = object.x + 5; or object.x = object.x – 5;

  5. I want a continuous shake. Means till the time I keep shaking my device, the ball in that keep bouncing. Whereas, shake event tracks shake only for once.

    Please help.

  6. how to know right-shake or left-shake
    thanks

Leave a Reply