April, 2012

  • DaveDev

    Accessing the Accelerometer in a Windows 8 Metro Style App using HTML and JavaScript

    • 1 Comments

    Overview

    I have recently been coding a Windows 8 Metro Style App using the new Windows 8 Release Preview bits and Visual Studio Express 2012 RC.  The app is going to be a retro shooter that takes advantage of HTML5 Canvas for the main game engine and then several Windows 8 Metro Style App Features.  Rather then wait for the game to be completely finished I figured I would start sharing some of my development experiences here on my blog.

    One of the first ideas I had was for a “Gravity Pulse” power that would be granted upon earning a predefined a amount of points (1,500 pts being the default).  Every time the user gains these amount of points a custom sound file will be played and then the screen will display a message to shake the device.  If the user shakes the device within a predefined amount of time all ships on the screen will blow up. 

    Gravity Pulse - Shake the Screen!

     

    The language I chose to use was HTML and JavaScript but this example could just have easily been done in C++/XAML or C#/XAML.  The code needed to access the accelerometer was very small and I was impressed just how easy it was to add to my game.

    Declaration and Initialization

    I start out by defining three local class variables I will use to access the sensor itself and default values for the polling interval.

    //accelerometer
       var accelerometer;
       var intervalId = 0;
       var getReadingInterval = 0;

    Once the DOM of the default.js page has been loaded I call a custom function (named initialize).

    //If Document fully loaded than begin processing
       document.addEventListener("DOMContentLoaded", initialize, false);

    Inside of initialize I set up all of my ships, the coordinate system for the gameboard and other important details.  There is a function I have created that will handle the accelerometer instance called initAccel.

    //Set up accelerometer for shake events
          initAccel();
    //Init Accelerometer
    function initAccel() {
        accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
        if (accelerometer) {
            // Choose a report interval supported by the sensor
            var minimumReportInterval = accelerometer.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            accelerometer.reportInterval = reportInterval;
            getReadingInterval = reportInterval * 2; // double the interval for display (to reduce CPU usage)
            
        } else {
           displayError("No accelerometer found");
        }
    }

    The initAccel function assigns the default accelerometer (through the magic of WinRT) to the class variable accelerometer and if it finds a device it sets up the reporting interval properties.  Reporting interval is how often we will receive new sensor readings from the accelerometer so it is important to pick a value that won’t kill our cpu.

     

    Handling the Accelerometer Readings

    Always remember accessing the sensor (as in any other devices) will cause cpu load and drain your battery.  I am careful to only turn the sensor on when the user hits the predefined amount of points and then I shut it off until the next gravity pulse becomes available.  Fortunately this is easy to do in JavaScript by controlling the eventListener.  If the accelerometer object has an eventListener assigned to it it will be actively polling for new data. 

    The function I use to check for an in progress Gravity Pulse is called updateScore.  This is where I start listening to accelerometer readings by assigning an eventListener for “shake events” as well as updating the screen and playing a wav file (more on playing sounds and external libraries to come)

    //update player score
        function updateScore(points) {
     
            score += points;
            scoreGravity += points;
            txtScore.innerHTML = "  Score: " + score;
     
            if (scoreGravity === GRAVITY_WAVE_PTS_REQ) {
                accelerometer.addEventListener("shaken", onShakenAccel);
                txtScore.innerHTML = " > SHAKE THAT SCREEN <";
                scoreGravity = 0;
                SoundJS.play("pulse", SoundJS.INTERRUPT_ANY);
            }
     
            //new level
            lvlNextPts = (lvlCurrent + 1) * LEVEL_PTS_REQ;
            if (score >= lvlNextPts) {
                lvlCurrent++;
                txtLevel.innerHTML = "Level: " + lvlCurrent;
                lvlDifficulty = LEVEL_SPEED_INCREASE * lvlCurrent;
     
                SoundJS.play("newlevel",SoundJS.INTERUPT_ANY);
     
            }
     
     
        }


    When a user shakes the Windows 8 tablet enough to register a “shake” event the onShakenAccel eventHandler is called and the following code invoked:

     

    //Accelerometer has been shaken and now we need to grant the bonus power
     function onShakenAccel(event) {
          //Stop Listening to Accelerometer
         accelerometer.removeEventListener("shaken", onShakenAccel);
     
         //Gravity Wave Power - Destroy all ships
         gravityWave();
        
     }

     

    You will notice the first thing I do is remove the eventListener which will effectively turn off the Accelerometer Sensor and then I call a custom function to blow up the on screen ships.

     

    Conclusion

    That’s it!  By adding a few eventListeners and a call into the WinRT Windows.Device.Sensors namespace my game has full accelerometer support!  Hopefully this post will help you get started in adding sensor support in your own Metro Style Apps.  As Always - if you are currently working on a Windows 8 app I would love to hear about it!

    You may also want to check out my previous Windows 8 Metro Style Development Tips:

  • DaveDev

    Want to win $20,000 with Windows Phone? Check out Dream.Build.Play!

    • 0 Comments

    Via Devfish..

    Here's the short version. Over 14? Write a cool Windows Phone Game and submit it to the Dream,Build,Play site. You could win up to $20,000. Yep, that's it. In a nutshell. So on to the long-winded stuff.

    Windows Phone the prizes are $20k, $10k, $5k, and $2500 respectively.

    The top 20 finalists will also get Phones. Want some inspiration, check out last year's XBOX winners at https://www.dreambuildplay.com/main/winners.aspx .

    Obviously the competition is going to be tough. Make something good. And if you publish it, let me know. I'm always looking for brag on our phone devs!

    RULES - SHORT LIST

    • Registration until May 15, Submission until June 12
    • Judging on fun/innovative/quality
    • Must be greater than 14 years old
    • All submissions are in English
    • You cannot submit if you live in Cuba, Iran, North Korean, Sudan or Syria

    Official Rules - https://www.dreambuildplay.com/main/officialrules.aspx

  • DaveDev

    Learn The Cloud. Make A Difference. @home with Windows Azure

    • 0 Comments

    Via my teammate Peter Laudati

    How does learning about cloud computing while contributing to scientific research sound to you? Join us for @home with Windows Azure to get a solid understanding of the Windows Azure platform while giving back to a very deserving cause.

    Learn the Cloud @home

    What is @home with Windows Azure?

    Microsoft provides a 90-day free trial of Windows Azure where you can kick the tires and run an application in the cloud 24x7, cost-free. Why not use that free compute time to give back to a deserving cause?  The @home with Windows Azure project is an online activity where you use those 90-days of free compute time (or your MSDN Subscriber benefits) to contribute to Stanford University’s Folding@home distributed computing project.

    The Folding@home project helps scientists provide insight into the causes of diseases such as Alzheimer’s, Mad Cow disease, ALS, and some cancer-related syndromes, by running protein folding simulations on thousands of machines world wide.

    You will deploy Stanford’s Folding@home application to Windows Azure, where it will execute protein folding simulations in the cloud, thus contributing to the research effort. In essence, your participation is a donation of your free compute time to the Folding@home project!

    Get Started

    It’s easy to get started in 4 quick steps. The @home with Windows Azure site has a series of short, easy to follow along to, screencasts that walk you through deploying Folding@home to the cloud!

    Learn The Cloud

    Want to go deeper? Join the @home team for a live webcast or catch one of their recordings on demand to learn more about Windows Azure, including: compute & storage services, debugging in the cloud, and patterns for achieving scale.

    Make A Difference

    In addition to directly contributing CPU cycles to the Folding@home project, from the start of March 2012, Microsoft is donating $10 (up to a maximum of $5000) to Stanford’s Pande Lab for everyone that participates!

    See Your Impact

    You can see your impact by visiting the detailed World Stats page on the @home with Windows Azure site.  For example, to date, over 6,300 VMs have contributed over 3.5 million compute hours!!!

    Learn more about the project and join in at the project’s website: http://distributedcomputing.cloudapp.net

Page 2 of 2 (7 items) 12