官术网_书友最值得收藏!

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:

  1. First, create a new PhoneGap project named accelobject by running the following command:
    phonegap create accelobject com.myapp.accelobject accelobject
    
  2. Add the device platform. You can choose to use Android, iOS, or both:
    cordova platform add ios
    cordova platform add android
    
  3. Add the device motion plugin by running the following command:
    phonegap plugin add org.apache.cordova.device-motion
    
  4. 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.
  5. The second div element will have the id of accelerometerData 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>
  6. 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:
  7. 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;
  8. 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();
    
    }
  9. 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);
    }
  10. 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.
  11. 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
    
    }
  12. The returned acceleration 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.
  13. To correctly interpret the acceleration results into pixels, use the vMultiplier variable to convert x and y into pixels:
    accelX = acceleration.x;
    accelY = acceleration.y;
    
    vy = vy + -(accelY);
    vx = vx + accelX;
    
    y = parseInt(y + vy * vMultiplier);
    x = parseInt(x + vx * vMultiplier);
  14. 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;
    }
  15. 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';
  16. 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.';
    }
  17. 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:
    <head>
      <style>
      div#dot {
        border-radius: 14px;
        width: 25px;
        height: 25px;
        background: #ff0000;
        position: absolute;
        top: 0px;
        left: 0px;
      }
      </style>
  18. 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 to do it…

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.

主站蜘蛛池模板: 松滋市| 延边| 阿拉善左旗| 桂平市| 鹿泉市| 闽清县| 湘乡市| 盐边县| 若尔盖县| 定日县| 太保市| 德惠市| 介休市| 彰化县| 开原市| 阿鲁科尔沁旗| 开原市| 阿鲁科尔沁旗| 津南区| 昭通市| 宜宾市| 调兵山市| 曲靖市| 昌乐县| 文化| 雅江县| 三明市| 长顺县| 蒙山县| 平果县| 盈江县| 邢台县| 周宁县| 思南县| 柳州市| 昌吉市| 漳平市| 洪雅县| 衡东县| 加查县| 民丰县|