Parallax 3D effect with Corona
This morning I implemented a simple parallax system that creates the illusion of depth by using gravity data from the accelerometer with Corona SDK
First, I start to poll the accelerometer 100 times per second.
1 |
system.setAccelerometerInterval( 100 ) -- 100 hz is max |
Gravity data from the accelerometer is then used to offset the angle of view. Illusion of depth is created by slightly moving the layers in the right direction, the magnitude of the movement depending on the distance to the eye.
To manage the scene I created 10 different layers. I placed the smaller shark in the front layer (layer 0), the larger shark in the middle (layer 5) and the back image to the background (layer 10).
Layer 0 has 0% displacement according to gravity, and Layer 10 has 100% displacement.
1 2 3 4 5 6 7 8 |
local displacementX = display.contentCenterX + (gravity.x * movementFactor) local displacementY = display.contentCenterY + ((gravity.y - calibrateY) * movementFactor) layer_10.x = displacementX layer_10.y = displacementY layer_5.x = displacementX * 0.5 layer_5.y = displacementY * 0.5 |
I like to use a calibrateY variable so I can reset the ‘default’ position for the phone. This way you can get a confortable angle when standing and sitting to use the demo.
Demo
Touch the small shark to calibrate and center the view.
Screenshot
Download
– Android APK
– Github