Using the Accelerometer
by Jon (Updated on 2014-01-30)
- Accelerometer Values
- How to Use the Values
- Challenge: Low Pass Filter
Some games use an accelerometer to create games a user can control by tilting the device. One famous example is the Labyrinth game.
You can access accelerometer data through a trio of blocks under the User Input > Mobile category in the Design Mode Palette.
The values of each of these range between -1.0 and 1.0 inclusive. Those values represent how much the device is tilted in a given direction.
For example, an x value of 1 would mean the user is tilting it all the way to the right. An x value of -1 would mean it’s tilted all the way to the left.
The values are flipped for a landscape oriented game. In other words, the values are always relative to portrait orientation and won't automatically adapt for a landscape game. See the example below for details.
- X (Positive) = Right
- X (Negative) = Left
- Y (Positive) = Up
- Y (Negative) = Down
- X (Positive) = Up
- X (Negative) = Down
- Y (Positive) = Left
- Y (Negative) = Right
How to Use the Values
To replicate a basic tilting motion on a landscape-oriented game, create a simple behavior as shown in the image below. You can adjust the value “-70” to another that suits your needs.
Why are x and y flipped? Shouldn't it be the other way around?
As stated in the previous section, the x and y values are flipped for landscape-oriented games because the device doesn't "know" that a game is oriented in landscape.
Why is it negative 70 rather than positive 70?
If you input positive 70, the game will act the opposite of what you'd expect. The reason is because the y-value of the accelerometer (which we are using to set the x-speed) is positive when tilted left and negative when tilted right.
However, since this is opposite of how Stencyl works (right is positive, left is negative), that's why the negative sign has to be there.
Challenge: Low Pass Filter
At times, you may find the accelerometer values to be overly sensitive, leading to jerky motion or motion where none is desired.
To combat this, add some logic to throw out low, absolute values, so that the device has to be tilted beyond some minimum theshold before responding.