This tutorial shows a little example how accelerometer can be used together with Box2d objects.
What we are going to do, is basically change gravity depending on phone rotation, so the object will allways fall down, relatively to real world's ground.
Let's take a draggable box2d body example as a start and modify it a bit.
First in the beginning of the file, we need to define, that we will be using accelerometer.
--include accelerometer require "accelerometer"
Then inside init function we start accelerometer and define some variables, which we will be using:
accelerometer:start() self.filter = 0.5 self.fx = 0 self.fy = 0 self.gravityScale = 10
Basically we will implement simple IIR filter and apply accelerometer data to world's gravity. Variable self.filter note's how much of last data we will use in current data. Use filter in interval between 0.5 to 1 to find whats suits you.
GravityScale is a variable, which will magnify accelerometer data (basically multiply by 10, in this example) for applying as gravity, to ensure it has some effect on box2d object (so that gravity won't be too small). You can also experiment with this value.
So all we need to do is to get new accelerometer data inside enter frame method, apply IIR filter to it and set it as gravity by multiplying with self.gravityScale.
-- get accelerometer values local x, y = accelerometer:getAcceleration() -- apply IIR filter self.fx = x * self.filter + self.fx * (1 - self.filter) self.fy = y * self.filter + self.fy * (1 - self.filter) --set world's gravity --for Portrait self.world:setGravity(self.fx*self.gravityScale, -self.fy*self.gravityScale) --for Landscape left --self.world:setGravity(-self.fy*self.gravityScale, -self.fx*self.gravityScale)
And of course, if we started accelerometer, at some point, we will want it to stop. So let's add stopping accelerometer inside onExitBegin method.
Now if you rotate your phone, you'll see that box2d world is changing gravity accordingly and you've created a mini Labyrinth game.
Unfortunately I can't make a video right now, but as usually, here is an example project for you to try. ;)