HTML5 to WinRT with Ultrabook Sensor Input

In a previous post I explained how adding sensors to HTML5 app is possible in Desktop mode but not yet supported. You can get it to work with a Google extension.  Read this post. http://software.intel.com/en-us/blogs/2012/09/18/adding-ultrabook-sensor-control-to-html5-apps for more information.

However accessing sensors in WinRT for a Windows Store app is very easy and well supported. To do this you will need Visual Studio 2012 Express for Windows 8 (free version works just fine). http://www.microsoft.com/visualstudio/eng/downloads

One really cool thing about developing a Windows Store app is that you can choose your language.  Javascript is fully supported, and by fully supported I mean you can drop in your HTML5 code with CSS, Canvas Element commands and it seems to work perfectly.  Also the support for mobile device features is well documented.  And for our example here, accessing sensors for input, You can find the code structure here for all device sensors  http://msdn.microsoft.com/library/windows/apps/windows.devices.sensors

In my previous blog I showed you could take a simple canvas application and add an event listener leveraging a Google Extension to use the Inclinometer for input in the app.  Turns out, that is exactly what you do with WinRT.  And to prove it I took the exact same code in my previous example and pasted in visual studio. 

See Video Demo

To get the sensors input to work I only added this code to the same HTML5 code shown in my previous blog.

   var accelerometer;
    accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
    accelerometer.addEventListener("readingchanged", onAccReadingChanged);
    function onAccReadingChanged(e) {
        var accelX = e.reading.accelerationX;
        var accelY = e.reading.accelerationY;
        var accelZ = e.reading.accelerationZ;
        xAngle = accelX * angleRate;  //note this takes the variable from event listener and assigns to a global variable
        yAngle = -accelY * angleRate; //note this takes the variable from event listener and assigns to a global variable
    }
 

This can be taken futher into a full HTML5 applications.  In this video I show how the same technique is used in an existing HTML5 game to turn the inputs from keyboard to sensor inputs.

Super simple!  The take-away here is that HTML5 is very portable between Desktop mode and Window Store apps. With just minor adjustments you can extend the value of existing HTML5 apps to work for both modes of Windows 8 and to leverage new sensor capabilities. To see the code snippet in context to the original code, below is the full code.  You can paste this into the default.html file of a new Visual Studio 2012 project, save and hit F5 to get it to work. If you have an device with sensors just move the device around and see the ship move.

 <html>
<head>
<script type="text/javascript">
    var context;
    var gamew = 1200;    //width of our game space
    var gameh = 600;     //height of our game space
    var shipSize = 60    //size of our ship
    var spin = 2;        //rate of spin
    var shipx = gamew / 2;       //origin of ship
    var shipy = gameh / 2;       // origin of ship
    var angleRate = 20;      //reduces or increases the angle by a rate   
    var xAngle = 0;  //global variable for horizontal angle of the device
    var yAngle = 0; //global variable for vertical angle of the device
    var accelerometer;
    accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
    accelerometer.addEventListener("readingchanged", onAccReadingChanged);
    function onAccReadingChanged(e) {
        var accelX = e.reading.accelerationX;
        var accelY = e.reading.accelerationY;
        var accelZ = e.reading.accelerationZ;
        xAngle = accelX * angleRate;
        yAngle = -accelY * angleRate;
    }
    setInterval(fallingship, 10);                // waits 10 milliseconds then repeats fallingship function
    function fallingship() {
        context = game_area.getContext('2d');      // context is the variable to envoke all Canvas commands
        context.clearRect(0, 0, gamew, gameh);      // Clears the entire screen
        context.strokeStyle = "white";                // Color of the object lines
        context.lineWidth = 2;
        context.fillStyle = "black";             // Color of the Game Space
        context.fillRect(0, 0, gamew, gameh);       //Draw Game Space  
        context.save();                          // Save the canvas location
        context.translate(shipx, shipy);      // Move the Canvas Coordinates to the ship X & Y position (remember this moves each time)
        context.rotate(spin * Math.PI / 180);    // Rotates the canvas according to the value of "spin" which is increaseing each frame      
        drawship();
        context.restore();                        // Restores our canvas (to its X&Y position - that way the game space rectangle is drawn at the same spot next time 
        spin++;                                  // Increases the rotation of our object 1 radian
        shipx += xAngle;              //shipx horizontal movementn increase or decreases according to the degree the device is held 
        shipy += yAngle;              //shipy vertical position increase or decreases according to the degree the device is held 
        collision()                                 // checks if ship has hit the edge of the game space
    }
    function collision() {
        if (shipx > gamew - shipSize / 2) {
            shipx = gamew - shipSize / 2;
        }
        if (shipx < 1 + shipSize / 2) {
            shipx = 1 + shipSize / 2;
        }
        if (shipy > gameh - shipSize / 2) {
            shipy = gameh - shipSize / 2;
        }
        if (shipy < 1 + shipSize / 2) {
            shipy = 1 + shipSize / 2;
        }
    }
 
    function drawship() {
        context.strokeStyle = "white";
        context.beginPath();
        context.moveTo(shipSize * -.3, shipSize * .2);
        context.lineTo(shipSize * -.4, shipSize * -.1);
        context.lineTo(shipSize * .1, shipSize * .4);
        context.lineTo(0, shipSize * .5);
        context.lineTo(shipSize * -.1, shipSize * .4);
        context.lineTo(shipSize * .4, shipSize * -.1);
        context.lineTo(shipSize * .3, shipSize * .2);
        context.moveTo(shipSize * -.4, shipSize * -.1);
        context.lineTo(shipSize * .3, shipSize * -.5);
        context.lineTo(0, shipSize * .3);
        context.lineTo(shipSize * -.3, shipSize * -.5);
        context.lineTo(shipSize * .4, shipSize * -.1);
        context.stroke();
    }
</script>
</head>
<body>
   <canvas id="game_area" width="1200" height="600"></canvas> <!--Add your Canvas app to your page-->
</body>
</html>
 

Для получения подробной информации о возможностях оптимизации компилятора обратитесь к нашему Уведомлению об оптимизации.
Теги: