Current Bloggers

Sponsors

Wikis

  • You have not yet contributed to any pages.

Building a Game With JavaScript: Making Things Move

Posted by Christopher Bennage, Wednesday, March 13, 2013 (3,836 views)

This is a continuation from the previous post.

Setting The Stage

The game we’re building will have waves of enemy ships fly in to attack the player’s units. Let’s begin by making a simple enemy as well as some dummy targets for them to attack. I’m going to keep the graphics very simple for the moment. Likewise we are going to focus on the enemy behavior and not worry about any player interaction just yet.

Here’s a demo of what we’ll make. Click on the start screen to transition into the game. The little yellow rectangles are our enemy ships. Each one projects its own target as a little red circle. Once it touches its target, it projects a new one and then flies toward it.

Let’s start from the top down. Our enemy units will “live” in our main screen for the game. (At least for the time being.) This screen needs to expose the same interface that we had for the start screen we made in the last post. We’ll also add a start method that we’ll call just once in order to initialize things.

Implementation

Here’s the implementation:

Explanation

The entities array will contain a list of the enemies we’re tracking. I used the name “entity” because this is a common term in game development. In general, it means something that has behavior and is drawn to the screen. Thus, you can expect entities to have update and draw methods. This is not a hard and fast definition though. You’ll find that the specifics of the definition can vary among engines, frameworks, and developers.

In our start function we populate entities by invoking our (as yet undefined) makeEnemyShip function. I’m passing in two numbers that makeEnemyShip will use to set the x and y position of the ship. I could have used random numbers or even hard coded values, however deriving from the loop’s controls makes it easy to cluster all the ships in the upper left corner of the screen.

The draw and update functions for the screen are very similar. They both iterate over entities and invoke the corresponding function on each entity. They also pass along the necessary context. For draw, this is the 2D drawing context of the canvas and for update it’s the elapsed time since the last frame.

Notice how the loop is structured differently from the loop in start. This is a performance optimization; though it has little consequence with so small an array. On some browsers, the call to length is a bit expensive. (Especially in cases when the array isn’t an array, but something that is array-like.) This adds up when you make the call once per iteration of the loop. We move it out of the loop so that we only call it once. Check out this test. Performance optimizations are tricky and change every time new browsers are released. It’s easy to get confused, and I recommend profiling your code frequently to look for hot spots rather than just guessing about optimizations. I hope to talk more about them later, but if you want more now check out the book High Performance JavaScript by Nicholas C. Zakas.

I had originally written my loops using the newer Array.forEach to iterate over entities. However, this proved to be significantly slower than a for loop.

The screen’s draw method also resets the canvas at the beginning of each iteration. If we did not do this, then every thing we drew on previous frames would still be present. For the start screen, I used clearRect however here I used fillRect with a solid color.

Here’s a function that will produce a simple enemy. It follows the same structure we’ve been using, update to handle the behavior and draw to actually draw it on the screen.

Some Bad Guys

Our enemy ships are a little more complicated than the screen they live on. Visually, they appear to have two components. The little yellow rectangle that moves about the screen and the phantom target that they project as a little red circle. In the final game, they will target one of the player’s units. However, the logic is very similar. In fact, it may become useful in debugging to how each enemy ship render something over it’s actual target.

Implementation

Explanation

Each enemy ship will be responsible for tracking its own state. In this code, the state is captured in a closure. In later code, we’ll track the track in a more traditional way. (I haven’t ran tests yet but I think that using a closure may have a performance impact.)

All of these variables represent the enemy ship’s state.

position is the location on the screen where we will render our ship.

Technically, the is the position in “world space”. World space is the logical space that entities in your game “live in”. This is distinct from “screen space”, which corresponds to the actual pixels on the screens. You can think of it this way: in your game you might have a circle with a radius of 10 and located at (100,100). However, where you draw it on the screen will depend upon where the player is viewing it from. If the player zooms in, the circle will grow larger but this doesn’t change the logical position or radius of the circle. We use the term “projection” to describe this. We project from world space into screen space based upon how the player is viewing the game world. The simplest project of course is just 1:1. Which means that there is no difference between world space and screen space. That’s what will stick with for the moment.

orientation is the direction the ship is currently facing. Our ship will always travel in the direction of its orientation. This constraints causes the ship travel in smooth arcs as opposed to abruptly changing its course.

turnSpeed and speed represent how quickly the ship can turn and how fast it can travel respectively. We won’t be modifying these values after setting them, which means the ship will turn and travel at constant rates. These values represent the rates of change for orientation and position. Note also, we defined turnSpeed in terms of fullCircle. This is an alias for Math.PI * 2; we are dealing in radians and not degrees.

target is a value with the shape { x: Number, y: Number }. The ship will always attempt to move towards this value by adjusting its orientation.

Update

The update function is the real meat of the enemy ship. First, we check to see if we are close to our target. If we are close enough, we consider our goal accomplished and we set a new target. Otherwise, we change our orientation so that we are flying toward our current target.

Here, x and y are really the distance between target and position along the respective axises. We want to know these values in order to calculate the distance between them. In general, you use the Pythagorean theorum to calculate distance. For deeper dive into the math, watch Distance Formula on Khan Academy. Finding the actual real distance uses a square root and calculating a square root is an expensive operation that’s best to avoid whenever you can.

We can bypass the need by working with the distance² (hence the variable name d2). We compare this against the hard-coded value of 16 (that’s 4²). In other words, if the distance between the ship and its target is less than 4 units we find a new target.

Once we’ve established what the ship’s target should be, we want the ship to move toward the target. As I’ve just mentioned, I’ve chosen to have the ship move at a constant speed. This means that it does not slow down or speed up. The only thing it can do is to change the direction it’s facing (orientation). These sort of constraints determine the personality and character of your game. Bear in mind, you don’t need to simulate the physics to have a fun game. Instead, you need to establish behaviors for your game entities that are merely fun. Fortunately, fun behaviors can often be easier to implement that the actual physics. I recommend taking a look at the demo and tweaking the turnSpeed and speed values to get a small taste for how the behavior can affect the game’s character.

In order to change the ship’s orientation we need to first determine where the ship ought to be facing. The values of x and y we just calculated can be interpreted as a vector. Meaning, it represents the direction and distance (magnitude) from the ship to the current target. To extract the actual angle (in radian) we use Math.atan2(x,y).

So now we have the direction the ship wants to face, angle, and the direction that it is facing, orientation. We calculate the difference between them and store it as delta.

The basic idea is that add the value of turnSpeed to orientation once each invocation of udpate until delta is 0 (meaning that the ship is flying directly at the target). However, some values of delta will cause the ship to “turn the wrong way”. For example, imagine that the ship is facing the top of the screen and that we’ve defined that as orientation === 0. Now, imagine that the target is directly to its right. The value of angle would be π/2 (or 90°). Adding turnSpeed to orientation each frame increments the value from 0 to π/2. However, if the target is directly to the left, then the value of angle would be 3π/2 (or 270°). Simply incrementing orientation would cause the ship to turn right and keep turning right. This is unintuitive behavior; we expect the ship to turn the shorted distance. In order to accomplish this, we translate any value of delta higher than π (180°) by subtracting fullCircle. This normalizes the value of delta between -π and π (or between -180° and 180°).

We take the absolute value of delta because otherwise we’d have to check for delta < -Math.PI as well. Also, we’ll use delta_abs again.

If delta is 0, we don’t need to change orientation. When it is different we need to modify the value of orientation.

First, we decide how much to change it using Math.min(turnSpeed, delta_abs). We could just use turnSpeed. However if we did it’s likely that delta would never quite be 0 and (depending on the size of turnSpeed) it could result is jittery motion. Secondly, we want to decided which direction to turn: positive values to the right and negative values to the left. We multiply the amount direction to change the sign, because direction will only ever be 1 or -1. Finally, we modulo orientation to ensure that it stays within a range of -2π to 2π. Otherwise, the calculation of delta would be off.

Our last step in update is to modifiy the actual position using the latest orientation and speed.

Some basic trigonometry is fairly fundamental for most game development. If you’re mathematically lost at this point, I recommend reviewing over at Khan Academey.

Here’s the geometric interpretation of the code. We want the ship to move a distance of speed in the direction of orientation. To do this, we need to project this vector (distance and direction) on the x and y axises. Since the distance is the length of the hypothenuse of right triangle, cosine gives us the x part and sine gives us the y part. We can then add these values to the current position.

Draw

Drawing the ship to the screen is a bit easier to follow. Here’s the flow of the logic:

  • Save the state of the drawing context.
  • Transform the context to make it easier to draw our ship.
  • Draw the ship.
  • Restore the context back to its original state.
  • Draw the target

Recall that ctx is the drawing context for the canvas. The context provide a useful API that allows us to move it around before we draw on it. This is analgous to having a sheet of paper that you might shift and rotate in order to make it easier to draw something complicated. This is the purpose of the translate and rotate methods.

First, we use ‘save’ to establishing a checkpoint for the drawing context that we can easily revert back to using ‘restore.’ The calls to translate and rotate modify the state of the drawing context. This modified state is very specific to the drawing of our enemy ship. If we didn’t translate and rotate the canvas, we’d have to do a lot more work to figure out where to draw the four corners of the rectangle.

I decided that I want my ship to be 6px long and 2px wide. Since I want the middle of the middle of my ship to be the point where it rotates, I shift by half the length and half the width. Hence, the values passed to ctx.fillRect(-3, -1, 6, 2). This point the new origin (0,0) at the middle of the rectangle, and it makes our call to rotate behave intuitively. If we used ctx.fillRect(0, 0, 6, 2) instead, then the ship would appear to rotate around its upper left corner. We’ll use these same techniques once we switch to using sprites.

After we restore the context’s state, we draw the target. We don’t bother using rotate because it’s meaningless to rotate a simple circle. Likewise, we don’t bother translate since the drawing logic is so simple.

The canvas is a broad topic in itself. I recommend taking a look at the tutorials over at MDN. A handy reference for the APIs themselves can be found on MSDN.

Comment on this post at dev.bennage.com
Discuss ()

Working on my first Pluralsight course – Html for the XAML Developer

Posted by Derik Whittaker, Friday, March 08, 2013 (2,702 views)

It’s official, I have been commissioned to author my first Pluralsight course and I am pretty excited.  My first course is going to be ‘Html for the XAML Developer’.  The objective for this course is to walk a XAML developer (Sliverlight, WPF, WP7, etc) through the process of porting a Silverlight application over to HTML.  I will accomplish this by breaking our reference application down into bit size chunks and rebuilding it in HTML.  In each step along the way I am going to compare our XAML code to our new HTML code in order to allow the view to understand how their existing knowledge can be applied to HTML.

In the course I am going to use the following tools:

  • jQuery
  • Knockout
  • Typescript
  • ASP.Net MVC
  • ASP.Net Web Api
  • Many, many others

 

Here is a screenshot of part of our reference XAML application

image

 

Here is what we expect to build via HTML

image

 

I am planning to have this course go live sometime in May so if your a pluralight subscriber please be sure to check it out when it does.

Till next time,

Discuss (13)

Knockout JS and mapping from Json to a custom object type

Posted by Derik Whittaker, Wednesday, March 06, 2013 (3,719 views)

One of the really cool features of Knockout js is the ability to take a raw json object, say from a web endpoint, and map it to an observable.  This is done via the mapping plug-in.

Take a look at the code below for an example

The magic above is the line ko.mapping.fromJS(item), this is what will take my json object and convert it to an observable.  Proof is below.

Below is the output via the Chrome Dev tools of our ‘item’ prior to mapping.  Notice we have raw properties.

image

 

Here is the output after the mapping, notice how now we have functions rather than properties.  This tells me I have a knockout observable.

image

There is one little issue here in the mapping above.  The issue is that the resulting type from the mapping is ‘object’.  Now this could be 100% ok but what if you want to custom object type for your binding.  Maybe you have computed properties you want to use as well.  Fortunately you can accomplish this via Knockout as well.

Assume I have this custom type as seen below (this is using TypeScript

How could I use Knockout mapping to returned a typed observable?

Turns out it is really simple.  The code below shows how

The ONLY difference in this code is in the ko.mapping.fromJs line.  Notice how I am passing in 2 extra arguments.  The 2nd argument is the one I want and this is the ‘target’ output type.

Now when I look at the output in the debugging tools I get what I want, a typed object being returned

image

So the trick to returned a typed observable is to use the overload of the .fromJS method.

Till next time,

Filed under: ,
Discuss (9)

Nuget Packages for Typescript Definition Files

Posted by Derik Whittaker, Sunday, February 24, 2013 (3,350 views)

If you have been using TypeScript you should be aware the definition file repository maintained by Boris Yankov called DefinitelyTyped.  This repository is awesome because it saves so much time and effort when working with 3rd party libraries with Typescript.

However, as great as this repository is it has always been painful getting the actual d.ts files for each library.  You would have to go to the site, navigate to the file, save the file and add it to your solution…. this sucked. 

If only there was a tool to help automate this?  Oh wait there is, it is called Nuget

I got the bright idea to start creating some Nuget packages around the d.ts files I am using so I posted them here.  The only problem with this is I was only creating the packages I cared about but more importantly I was creating these by hand and that is time consuming and I am lazy.

But yesterday I received some awesome news from Jason Jarret (aka @staxmanade) on twitter as seen below

image

This is awesome news.  Now all the d.ts files hosted in the DefinitelyTyped repository now have Nuget pacakges… w00t!

To see the list of Nuget packages follow this link.

Awesome work Jason,

Till Next Time,

P.S. I will be taking my nuget packages offline very shortly as they should not be used anymore.

Discuss (8)

Introducing Durandal

Posted by Rob Eisenberg, Monday, February 18, 2013 (5,733 views)

Today I'm very excited to officially bring to you Durandal!

Durandal is a new open source JavaScript library for rich client application development. It focuses on providing an enjoyable and productive developer experience centered around simple conventions and standard patterns like MVC, MVP and MVVM. Durandal is built on libs you know and love like jQuery, Knockout and RequireJS, so there's little to learn and building apps feels comfortable and familiar.

Here's a short list of it's features:

  • Clean MV* Architecture
  • JS & HTML Modularity
  • Simple App Lifecycle
  • Eventing, Modals, Message Boxes, etc.
  • Navigation & Screen State Management
  • Consistent Async Programming w/ Promises
  • App Bundling and Optimization
  • Use any Backend Technology
  • Built on top of jQuery, Knockout & RequireJS
  • Integrates with other libraries such as SammyJS & Bootstrap
  • Make jQuery & Bootstrap widgets templatable and bindable (or build your own widgets).

I'm also pleased to announce that I've been working with the ASP.NET team to bring Durandal to you as an ASP.NET MVC Template, released today and compatible with the new Web Tools 2012.2 release. You can grab the VSIX, install it and get started very quickly building rich web apps now. If using the VSIX isn’t your style, we’ve got several nuget packages available too. Finally, if you just love NodeJS, you might be interested in using our Mimosa skeleton.

To  learn more, please visit the official site, where you will find the getting started guide, documentation, videos, training and commercial support options.

Stay tuned. There's lots to say about Durandal and I look forward to sharing it with you in the coming weeks and months.

Discuss (22)

Entity Frame Performance Gotcha

Posted by Derik Whittaker, Tuesday, February 12, 2013 (6,119 views)

I was doing some profiling of our Entity Framework stuff via EFProfiler the other day and noticed something really odd.  When I was watching the profiler I noticed that I had a query returning back over 1300 results and that was NOT right, I had expected only 1 result.  I looked the resulting sql and immediately I ‘thought’ I knew the issue.  I thought the issue was that I had not setup my where clause correctly in my EF… Turns out I was both right and wrong at the same time.

Below is a sample of my EF code

** note that I replaced the dynamic variables w/ static for testing inside of LinqPad **

image

When I run these statements above and look at the resulting sql in LinqPad I would expect to see 2 queries.  Sure enough I did have 2 of them.  What shocked me was that the 2nd query ONLY did a where clause filter on ClientID (see below)

image

This had a resulting output of below, which is the expected result

image

But if you run the sql generated above (2nd statement) you actually get 1327 results.  This tells me that indeed the ENTIRE result for a client was being pull out of the DB, pulled over the wire and filtered down on the client…This is not good.

Now I tried a few different things to see if I could get different results such as doing a .FirstOrDefault rather than a .Where… No dice

Finally one of my coworkers found this Stack Overflow link which talks directly to this issue.

Turns out this behavior is by design and I had never noticed it before.  I (and 3 of my coworkers mind you) had just assumed that when EF did a lazy load off of a previously fetched IQueryable it would include any filter statements and pass those to the SERVER.  But because the .Images is NOT a IQuerable but rather an EntitySet<T> it did not work as expected.

To solve this issue I simply just changed my statement to go directly at my EF context for the ONE row I wanted w/ both keys (client and type).  This solved my issue as well as give me a pretty significant performance enhancement.

image

Long story short is that if you are going to lazy gather data in EF make sure you are doing your filtering on the server rather than the client and make sure you understand that an EntitySet does NOT do this only an IQuerable does this.

Till next time,

Filed under: , ,
Discuss (14)

Help I am getting an XMLHttpRequest exception of Access-Control-Allow-Orig

Posted by Derik Whittaker, Sunday, February 10, 2013 (3,450 views)

When working on a demo application recently I was trying to get an ajax call to hit one of my Web API routes and I was immediately hit with the following exception.

XMLHttpRequest cannot load http://localhost:33884/api/ToDo/. Origin http://localhost:3462 is not allowed by Access-Control-Allow-Orig

Of course this sucked because I KNEW what the issue was but not exactly how to solve it.  Well solve it the way I wanted.  Of course i could have just put both my sites (MVC project and WebAPI project) under the same web application in IIS to remove this but that was not an acceptable answer for my needs.

After a bit of searching online I thought I came across an solution that would work.  I thought that I could just set the crossDomain switch in my ajax call as below to get it to work, but no dice.

I found another suggestion telling me to change the dataType of request form json to jsonp as below, but as you may have guessed that did not work.

Finally at a bit more searching I found more information which suggested I needed to add a response header on the server side to allow ‘Access-Control-Allow-Origin’ and this Stack Overflow answer gave me all the details needed to make this happen in Web API.  Once I implemented the solution inside my WebApi endpoints and REMOVED the 2 un-needed attributes in my .ajax call the world was a happy place and I was able to make cross domain calls to my other services.

Till next time,

Discuss (10)

How to use the Accelerometer in Windows 8 C#/XAML Applications

Posted by Derik Whittaker, Sunday, January 27, 2013 (4,095 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Accelerometer Sensor.  The Accelerometer sensor can be used to get a acceleration force of the device on the x y and z axis, or basically measure how fast it is moving in any given direction.  With the Accelerometer you could build interesting augmented reality applications which react to the forces of the device.  In this post we are going to take a look at how to use the Accelerometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Inclinometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Accelerometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

Apart from being able to get the changed events for the Accelerometer you can also detect if the device has been shaking by listing to those events as well.

Register to receive event updates when the Accelerometer shaek change

In the above code I am wiring an event to tell me each time the Accelerometer notices the device has been shaken.

Handle the Shaken Event and do something.

In the above code I have received the Shaken Event and I am simply updating a counter.  Of course in a real world app you would want to do something a bit more exciting, but this gets the point across.

As you can see working with the Accelerometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (11)

Handling Resuming in your Windows 8 Applications

Posted by Derik Whittaker, Saturday, January 26, 2013 (4,171 views)

Windows 8 applications (aka Windows Store applications) have 3 different life cycle states they can go through:

  1. Launching
  2. Suspending
  3. Resuming

Handling both Launching and Suspending is pretty much covered out of the box but what if you need to resume from a suspended state?  In most normal scenarios you should not have to do too much here because the built in SuspensionManager (this is generated code, not framework code) will handle putting your application back together in terms of what page your user was on and how the page/screen was populated when it was suspended.

However, if you are using data which is gathered from a remote source such as a web service you may want to refresh your application when it is resuming from suspension.  But how exactly can we accomplish this?

Hooking up the Resuming Event

You need to wire up the .Resuming event inside your App.cs class.  By default the template only wires the Suspending event as it is used in almost every application.

Handling the Resuming Event

As you can see above it does take some effort to get to your underlying viewmodel in order to make the Resume() call but it is well worth it.

We first need to get the current frame.  Once we have the frame we want to check to ensure it is of the correct type in order to further check its underlying data context.  Finally we want to check out data context to ensure it is of the correct type.  Doing this final  check will safe guard us and allow us to only make the resume calls on pages which require it.

Doing something useful in our Resume() call

In the Resume() is where you would need to handle any remote data fetching or updating of existing data.

Defining our IResumable interface

Our above interface is small, but it does the trick.  It allows us to identify which pages need to be resumed and enables a way to make the call

As you can see handling the Resuming event in a Windows 8 application is not hard, however getting to your underlying data context does take a bit of work, but this work is well worth it in my opinion.

Till next time,

Filed under: , , ,
Discuss (6)

How to use the Inclinometer sensor in Windows 8 C#/XAML applications

Posted by Derik Whittaker, Wednesday, January 23, 2013 (3,747 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Inclinometer Sensor.  The Inclinometer is a sensor which allows you to measure the movement of the device in terms of Pitch, Roll and Yaw, or more simply rotation of the device on the X, Y and Z axis.  With the Inclinometer you could build interesting augmented reality applications which react to the movement of the device.  In this post we are going to take a look at how to use the inclinometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Inclinometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Inclinometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

As you can see working with the Inclinometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (9)

How to use the Gyrometer Sensor in Windows 8 C#/XAML applications

Posted by Derik Whittaker, Monday, January 21, 2013 (3,659 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

  • Light Sensor
  • Gyrometer Sensor (this post)
  • Inclinometer Sensor (future post)
  • Accelerometer Sensor (future post)

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Gyrometer Sensor.  The Gyrometer sensor can be used to get a angular velocity of the device on the X, Y and Z axis.  In this post we are going to take a look at how to use the Gyrometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Gyrometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Gyrometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

As you can see working with the Gyrometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (8)

Caliburn.Micro v1.4.1 Released

Posted by Rob Eisenberg, Sunday, January 20, 2013 (6,240 views)

I’m labeling this the  Thomas Ibel/Nigel Sampson release. Why? Because these two hardworking gentlemen have put great effort into bringing you the most mature version of Caliburn.Micro yet. In the two months since our 1.4 release they’ve dealt with almost every outstanding issue on our list. Great work guys! In addition to bug fixes, there’s been some minor enhancements, we’ve synced up the latest WUI library and added official support for WPF 4.5. You can get it on Nuget now. Enjoy!

On Testing: Why write tests?

Posted by Krzysztof Koźmic, Saturday, January 19, 2013 (4,748 views)

This post is secod part of my Back to basics: on testing series.

Developers writing tests

People new to software, or coming from organizations where all testing is done by dedicated people often find the idea of developers doing testing bizarre.

After all, we're the highly trained, educated professionals. We get payed to do the hard bits. Clicking around the UI to see if a label is misaligned or an app crashed surely should be delegated to somebody else, outsourced even.

Truth is, there are various kinds of tests, and while there is value in UI tasting (automated or not) we'll concetrate at somethig else first.

You write the tests for your future self

The idea of developers writing tests came not from academia but from the field. From people who spent years developing successful software. And as you get out there, and start working with teams of people, on real life big systems that solve real problems, you realise that some things you belived (or in fact were taught) to be true, are not.

We'll get into the details as we progress with this series, but let's start with the biggest one:

The code is written, and read, and read, and read and read some more and modified, and read, and modified again, and read some more again and then few months later read yet again and again

You may notice there's much more reading than writing there. That is true for most code - you don't just write and forget it, like is the case with coding assignments at unversity. Real-life code is long lived, often expanded and modified and commonly the person doing the expanding is not the person who originally wrote the code. In fact the original author may have already moved on to work elsewhere.

  • How do you know what the code does?

  • How do you know where to make the change?

  • How do you know your change didn't break any of the assumptions that code interacting with the bit you changed makse about it?

  • How do you know the change you made works the way you wanted it to?

  • How do you know the API you created (in other words the public methods) are easy to use and will make sense to the other developers using it (that may also be you few weeks from now!).

These are the reasons for writing tests. Tests are the most economical way of ensuring the change you will make two months from now fit in the design constrants you designed today. Tests are the fastest way for other developers (or again, future you) to get a feel of how a piece of code works; what it does, and how you're supposed to use it.

Don't just take my word for it

In the next part of the series we'll start looking at actual code, writing some tests, and explaining the concepts around them.

Until then, if you have any questions, or suggestions as to what to cover in future posts of the series, feel free to leave a comment.

Filed under: ,
Discuss (0)

How to use the Light Sensor in Windows 8 C#/XAML applications

Posted by Derik Whittaker, Wednesday, January 16, 2013 (3,667 views)

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Light Sensor.  This sensor can be used for many things and it is common that the light sensor is used to illuminate the backlight on keyboards.  In this post we are going to take a look at how to use the Light Sensor from within your C#/XAML Windows 8 application.

Before we get started we should understand what the light sensor reading is providing you.  This sensor will give you the ‘Lux Values’ (which is lumens per square meter) from the ambient light in your area.  The Lux values can be described in the chart below and you can get more details by looking at the MSDN link here

image

Now on to how to use the Light Sensor

In the code above I have done 2 things:

  1. Created a instance property for the LightSensor
  2. Retrieved the current light sensor and done a check to see if it is null.  It being null will indicate that your device does not have a sensor

Register to receive updates from the sensor as the values change

Now that we have our light sensor we want to register for its updates.  To do this we can either ask the sensor for its reading one time, we can poll the sensor or we can register for an ‘ReadingChanged’ event.  I am going to do the register for updates via the event.

The above code will simply register/unregister the event handler based on the provided flat.

Getting the reading once or via Polling

If you would like to simply get the Lux value one time you could just do the following

Doing something useful w/ the Lux values

Two things should stand out from the above code.

  1. I am using the async/await keywords, this just helps w/ the UI responsiveness
  2. I am using a dispatcher to push the UI changes.  I get access to the dispatcher by passing it into my ViewModel via the constructor and I am passing in an instance of Window.Current.Dispatcher

Now once I have access to the  reading above I am simply pushing this value to the UI for display but it is here that you may want to do something useful

As you can see working with the light sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (12)

Building a Game With JavaScript: Start Screen

Posted by Christopher Bennage, Monday, January 14, 2013 (4,298 views)

This is a continuation from the previous post.

Specification

Many games have a start screen or main menu of some sort. (Though I love games like Braid that bypass the whole notion.) Let’s begin by designing our start screen.

We’ll have a solid color background. Perhaps the ever lovely cornflower blue. Then we’ll draw the name of our game and provide an instruction to the player. In order to make sure we have the player’s attention, we’ll animate the color of the instruction. It will morph from black to red and back again.

Finally, when the player clicks the screen we’ll transition to the main game. Or at least we’ll stub out the transition.

Here’s a demo based on the code we’ll cover later in this post (as well as that from the previous post.)

Implementation

Here’s the code to implement our start screen.

(Go look at the Gist.)

Explanation

Recall that our start screen is meant to be invoked by our game loop. The game loop doesn’t know about the specifics of the start screen, but it does expect it to have a certain shape. This enables us to swap out screen objects without having to modify the game loop itself. The shape that the game loop expects is this:

{
    update: function(timeElapsedSinceLastFrame) { },
    draw: function(drawingContext) { }
}

Update

Let’s begin with the start screen’s update function. The first bit of logic is this:

hue += 1 * direction;
if (hue > 255) direction = -1;
if (hue < 0) direction = 1;

Perhaps hue is not the best choice of variable names. It represents the red component for an RGB color value. The range of values for this component is 0 (no red) to 255 (all the reds!). On each iteration of our loop we “move” the hue towards either the red or black.

The variable direction can be either 1 or -1. A value of 1 means we are moving towards 255 and a value of -1 means we are moving towards 0. When we cross a boundary, we flip the direction.

Keen observers will ask why we bother with 1 * direction. In our current logic, it’s an unnecessary step and unnecessary steps in game development are generally bad. In this case, I wanted to separate the rate of change from the direction. In order words, you could modify that expression to 2 * direction and the color would change twice as fast.

This leads us to another important point. Our rate of change is tied to how quickly our loop iterates; most likely 60fps. However, it’s not guaranteed to be 60fps and that makes this approach a dangerous practice. Once way to detach ourselves from the loop’s speed would be to use the elapsed time that is being passed into our update function.

Let’s say that we want to it to take 2 full seconds to go from red to black regardless of how often the update function is called. There’s a span of 256 discrete values between red and black. To make our calculations clear, let’s say there are 256 units and we’ll label these units R. Also, the elapsed time will be in milliseconds (ms). For a given frame, if were are given a slice of elapsed time in ms, we’ll want to calculate how many R units to increase (or decrease) hue by for that slice. Our rate of change can be defined as 256 **R** / 2000 **ms** or 0.128 R/ms. (You can read that as “0.128 units of red per millisecond”.) This rate of change is a constant for our start screen and as such we can define it once (as opposed to calculating it inside the update function).

Now that we have the rate of change , we only need to multiply it by the elapsed time received in update to determine how many Rs we want. A revised version of the function would look like this:

var rate = 0.128; // R/ms

function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue > 255) direction = -1;
    if (hue < 0) direction = 1;
}

One consequence of this change is that hue will no longer be integral values (as much as that can be said in JavaScript.) This means that we’d really want to have two values for the hue: an actual value and a rounded value. This is because the RBG model requires an integral value for each color component.

function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue > 255) direction = -1;
    if (hue < 0) direction = 1;

    rounded_hue = Math.round(hue);
}

Draw

Let’s turn our attention to draw for a moment. One of the first things you generally do is to clear the entire screen. This is simple to do with the canvas API’s clearRect method.

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

Notice that ctx is an instance of CanvasRenderingContext2D and not a HTMLCanvasElement. However, there is a handy back reference to the canvas element that we use to grab the actual width and height.

There are other options other than clearing the entire canvas, but I’m not going to address this in this post. Also, there are some performance considerations. See the article listed under references.

After clearing the screen, we want to draw something new. In this case, the game title and the instructions. In both cases I want to center the text horizontally. I created a helper function that I can provide with the text to render as well as the vertical position (y).

function centerText(ctx, text, y) {
    var measurement = ctx.measureText(text);
    var x = (ctx.canvas.width - measurement.width) / 2;
    ctx.fillText(text, x, y);
}

measureText returns the width in pixels that the rendered text will take up. We use this in combination with the canvas element’s width to determine the x position for the text. fillText is responsible for actually drawing the text.

The rendering context ctx is stateful. Meaning that, what happens when you call methods like measureText or fillText depends on the state of the rendering context. The state can be modified by setting its properties.

var y = ctx.canvas.height / 2;
ctx.fillStyle = 'white';
ctx.font = '48px monospace';
centerText(ctx, 'My Awesome Game', y);

The properties fillStyle and font change the state of the rendering context and hence affect the methods calls inside of centerText. This state applies to all future methods calls. This means that all calls to fillText will use the color white until you can the fillStyle.

Notice too that we are calculating the x and y values for the text on every frame. This is potentially wasteful since these values are unlikely to change. However, if we want to respond to changes in canvas size (or even changes to the text itself) then we’d want to continue calculating these on every frame. Otherwise, if we were confident that we didn’t need to do this, we could calculate these values once and cache them.

Now let’s use the red component calculated in update to render the instructional text.

var color = 'rgb(' + hue + ',0,0)';

ctx.fillStyle = color;
ctx.font = '24px monospace';
centerText(ctx, 'click to begin', y + 30);

fillStyle can be set in a number of ways. Earlier, we used the simple value white. Here were are using rgb() to set the individual components explicitly. Any CSS color should work with fillStyle. (I won’t be too surprised if some don’t though.)

Now you might be wondering why we bothered calculating hue inside update since hue is all about what to draw on the screen. The reason is that draw is concerned with the mechanics of rendering. Anything that is modeling the game state should live in update. The tell in this example is that hue is dependent on elapsed time and the draw doesn’t know anything about that.

Update (again)

Moving back to update, the next bit deals with input from the player. In the sample code I’ve extracted the input logic away. The key thing here is that we are not relying on events to tell us about input from the player. Instead we have some helper, input in this case, that gives us the current state of the input. If event-driven logic says “tell me when this happens” then our game logic says “tell me if this is happening now”. The primary reason for this is to be deterministic. We can establish at the beginning of our update what the current input state is and that it won’t change before the next invocation of the function. In simple games this might be inconsequential, but in others it can be a subtle source of bugs.

var isButtonDown = input.isButtonDown();

var mouseJustClicked = !isButtonDown && wasButtonDown;

if (mouseJustClicked && !transitioning) {
    transitioning = true;
    // do something here to transition to the actual game
}

wasButtonDown = isButtonDown;

We only want transition when the mouse button has been released. In this case, “released” is defined as “down on the last frame but up on this one”. Hence, we need to track what the mouse button’s state was on the last frame. That’s wasButtonDown and it lives outside of update.

Secondly, we don’t want to trigger multiple transitions. That is, if our transition takes some time (perhaps due to animation) then we want to ignore subsequent clicks. We have our transitioning variable outside of update to track that for us.

More to come…

Reference

Comment on this post at dev.bennage.com
Discuss ()
More Posts « Previous page - Next page »

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)