Some time ago I introduced my drawing app. The app implementes some neat ideas, like mirroring the canvas, by rotating the device by 180°. Now I wanted to implement “shake-to-reset”, like shaking the device to erase canvas and reset the colors, etc. But there was no native option for shake detection. So I used the accelometer and created a function, which you can run inside draw() to check whether the device is being shaked or not.
Shake your device a few times and you should get a message in the output window - or shake it continuously…
-- Accelometer Shake supportedOrientations(LANDSCAPE_RIGHT) function setup() print("Shake a few times until the rect() exceeds the ellipse().") end local function deviceShaking() local acceleration = UserAcceleration local intensity = 4 -- adjust min. shaking intensity to trigger this event! if UserAcceleration.x > intensity or acceleration.y > intensity or acceleration.z > intensity then _deviceShakeUpdatedAt = ElapsedTime _deviceShakeBegunAt = _deviceShakeBegunAt or ElapsedTime -- first shake triggers listening process -- listen if shaking continues for [x] seconds then device is considered shaking on purpose if (ElapsedTime - _deviceShakeBegunAt) >= .5 then return true end end if _deviceShakeUpdatedAt and (ElapsedTime > (_deviceShakeUpdatedAt + .5)) then _deviceShakeBegunAt = nil _deviceShakeUpdatedAt = nil end return false end function draw() if deviceShaking() then print("DEVICE SHAKING") background(255, 60, 25) else background(100) end translate(WIDTH/2, HEIGHT/2) noFill() stroke(0) strokeWidth(2) rectMode(CENTER) ellipse(0, 0, 100) rect(UserAcceleration.x * 40, UserAcceleration.y * 40, 10) end ```