Updating a display object position through accelerometer events
Developers can make use of the accelerometer sensor and continual updates provided by it for many purposes, including motion-detection games and updating the position of an object on the screen.
How to do it…
We will use the device's accelerometer sensor on continual update to move an element around the screen as a response to device movement:
First, create a new PhoneGap project named accelobject by running the following command:
Open www/index.html and clean up unnecessary elements. Within the body tag create two div elements. Set the first with the id attribute equal to dot. This will be the element that will move around the screen of the device.
The second div element will have the id of accelerometerData and will be the container into which the returned acceleration data will be output:
You can now start with the custom scripting and PhoneGap implementation. Add a script tag block before the closing head tag to house the code:
Before diving into the core code, you need to declare some variables. Here, set a default value for watchID as well as the radius for the circle display object you will be moving around the screen:
// The watch id variable is set as a
// reference to the current `watchAcceleration`
var watchID = null;
// The radius for our circle object
var radius = 50;
Now declare the event listener for the deviceready event, as well as the onDeviceReady function, which will run once the native PhoneGap code has been loaded:
// Set the event listener to run when the device is ready
document.addEventListener("deviceready", onDeviceReady, false);
// The device is ready so let's
// start watching the acceleration
function onDeviceReady() {
startWatch();
}
The onDeviceReady function will execute the startWatch method, which sets the required frequency for accelerometer updates and makes the request to the device to obtain the information:
// Watch the acceleration at regular
// intervals as set by the frequency
function startWatch() {
// Set the frequency of updates from the acceleration
var options = { frequency: 100 };
// Assign watchAcceleration to the watchID variable
// and pass through the options array
watchID =
navigator.accelerometer.watchAcceleration(
onSuccess, onError, options);
}
With the request made to the device, it is time to create the success and error handling methods. The onSuccess function is first, and this will deal with the movement of our object around the screen.
To begin, you need to declare some variables that manage the positioning of the element on the device:
function onSuccess(acceleration) {
// Initial X Y positions
var x = 0;
var y = 0;
// Velocity / Speed
var vx = 0;
var vy = 0;
// Acceleration
var accelX = 0;
var accelY = 0;
// Multiplier to create proper pixel measurements
var vMultiplier = 100;
// Create a reference to our div elements
var dot = document.getElementById('dot');
var accelElement =
document.getElementById('accelerometerData');
// The rest of the code will go here
}
The returnedacceleration object contains the information you need regarding the position on the x and y axis of the device. You can now set the acceleration values for these two axes in the variables and work out the velocity for movement.
To correctly interpret the acceleration results into pixels, use the vMultiplier variable to convert x and y into pixels:
Ensure that the display object doesn't move out of sight and remains within the bounds of the screen:
if (x<0) { x = 0; vx = 0; }
if (y<0) { y = 0; vy = 0; }
if (x>document.documentElement.clientWidth-radius) {
x = document.documentElement.clientWidth-radius; vx = 0;
}
if (y>document.documentElement.clientHeight-radius) {
y = document.documentElement.clientHeight-radius; vy = 0;
}
Now that you have the correct x and y coordinates, you can apply them to the style of the dot element position. Also create a string message containing the properties returned from the acceleration object as well as the display coordinates that have been created:
// Apply the position to the dot element
dot.style.top = y + "px";
dot.style.left = x + "px";
// Output the acceleration results to the screen
accelElement.innerHTML =
'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp +
'<br />' +
'Move Top: ' + y + 'px<br />' +
'Move Left: ' + x + 'px';
The call to the accelerometer also requires the error handler, so let's write that now. Create a simple string message and insert it into the div element to inform the user that a problem has been encountered:
// Run if we face an error
// obtaining the accelerometer data
function onError() {
// Handle any errors we may face
var accelElement =
document.getElementById('accelerometerData');
accelElement.innerHTML =
'Sorry, I was unable to access the acceleration data.';
}
Finally, add in some CSS to create the dot marker used to display the position on the device. Place the following CSS within the style tag in the head element:
Upon running the application, you will be able to move the element around the screen by tilting the device. This would look something like this:
How it works…
By implementing a constant request to watch the acceleration and retrieve movement results from the device, we can pick up changes from the accelerometer sensor. Through some simple JavaScript, we can respond to these changes and update the position of an element around the screen based upon the returned sensor information.
In this recipe, we are easily changing the position of the dot element by calculating the correct x and y axis to place it on the screen. We are also taking extra care to ensure that the element stays within the bounds of the screen by using some conditional statements to check the current position, the radius of the element, and the dimensions of the screen itself.