- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 1063字
- 2021-07-09 21:26:47
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:phonegap create accelobject com.myapp.accelobject accelobject
- Add the device platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the device motion plugin by running the following command:
phonegap plugin add org.apache.cordova.device-motion
- Open
www/index.html
and clean up unnecessary elements. Within thebody
tag create twodiv
elements. Set the first with theid
attribute equal todot
. This will be the element that will move around the screen of the device. - The second
div
element will have theid
ofaccelerometerData
and will be the container into which the returned acceleration data will be output:<html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="msapplication-tap-highlight" content="no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <title>Hello World</title> </head> <body> <h1>Accelerometer Movement</h1> <div id="dot"></div> <div id="accelerometerData">Obtaining data...</div> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> </script> </body> </html>
- You can now start with the custom scripting and PhoneGap implementation. Add a
script
tag block before the closinghead
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 theonDeviceReady
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 thestartWatch
method, which sets the requiredfrequency
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 returned
acceleration
object contains the information you need regarding the position on thex
andy
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 convertx
andy
into pixels:accelX = acceleration.x; accelY = acceleration.y; vy = vy + -(accelY); vx = vx + accelX; y = parseInt(y + vy * vMultiplier); x = parseInt(x + vx * vMultiplier);
- 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
andy
coordinates, you can apply them to the style of thedot
element position. Also create a string message containing the properties returned from theacceleration
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 thestyle
tag in thehead
element:<head> <style> div#dot { border-radius: 14px; width: 25px; height: 25px; background: #ff0000; position: absolute; top: 0px; left: 0px; } </style>
- 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.
- Angular UI Development with PrimeNG
- Python自動化運維快速入門
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- 編程數(shù)學
- MATLAB 2020從入門到精通
- Swift語言實戰(zhàn)精講
- 焊接機器人系統(tǒng)操作、編程與維護
- Python大學實用教程
- 微課學人工智能Python編程
- Julia數(shù)據(jù)科學應用
- Tableau Desktop可視化高級應用
- Vue.js光速入門及企業(yè)項目開發(fā)實戰(zhàn)
- Modernizing Legacy Applications in PHP
- Android應用開發(fā)攻略
- 熱處理常見缺陷分析與解決方案