Moving to New York!

So, it’s official … in a few months, I will be moving up to NY. I’m pretty excited about the prospect, and the family is on board. We are going to visit for a week in the near future to start checking some schools and neighborhoods … any suggestions or tips would be greatly appreciated :-)

Comments (2)

ASP.NET MVC Charts

There are a few references online about how to get the new ASP.NET Charting controls working with the MVC framework. However, some of them are outdated, and the corresponding information to make it work with MVC2 are spread out. So in an effort to organize the info all in one place, here’s a quick step by step guide on how to get this working :-)

First step is to add a reference to the System.Web.DataVisualization assembly

Next create a new charting controller (or simply add the action method below to an existing controller).

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;

namespace Phoenix.Portal.Controllers
{
    public class ChartController : Controller
    {
        private Font font = new Font("Trebuchet MS", 14, FontStyle.Bold);
        private Color color = Color.FromArgb(26, 59, 105);

        public ActionResult Index()
        {
            // Define the Data ... this simple example is just a list of values from 0 to 50
            List<float> values = new List<float>();
            for (int i = 0; i < 50; i++)
            {
                values.Add(i);
            }

            // Define the Chart
            Chart Chart2 = new Chart()
            {
                Width = 800,
                Height = 296,
                RenderType = RenderType.BinaryStreaming,
                Palette = ChartColorPalette.BrightPastel,
                BorderlineDashStyle = ChartDashStyle.Solid,
                BorderWidth = 2,
                BorderColor = color
            };
            Chart2.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;

            Chart2.Titles.Add(new Title("Do The Wave!", Docking.Top, font, color));
            Chart2.ChartAreas.Add("Waves");
            Chart2.Legends.Add("Legend");

            //Bind the model data to the chart
            var series1 = Chart2.Series.Add("Sin");
            var series2 = Chart2.Series.Add("Cos");

            foreach (int value in values)
            {
                series1.Points.AddY((float)Math.Sin(value * .5) * 100f);
            }

            foreach (int value in values)
            {
                series2.Points.AddY((float)Math.Cos(value * .5) * 100f);
            }

            // Stream the image to the browser
            MemoryStream stream = new MemoryStream();
            Chart2.SaveImage(stream, ChartImageFormat.Png);
            stream.Seek(0, SeekOrigin.Begin);
            return File(stream.ToArray(), "image/png");
        }
    }
}

Finally, show the chart by pointing to the controller’s path:

<img src="/chart" />

And that’s it! You get a sweet chart as seen below:

Comments (2)

Smooth Control with Touch

The new touch capabilities that are present in XNA 4.0/windows phone 7 present new opportunities for letting the user take control of the games that we can write. Unlike the input from the xbox 360 gamepad, or the mouse though, the user is not restricted to incremental analog adjustments (ie. moving the mouse by 5 pixels per frame, or having the left stick pushed up to a value of .5). So it is completely possible for the user to press his finger in the bottom left of the screen, drag it 20 pixels, lift for 5 seconds, and then press it down somewhere in the upper right of the screen.

In a naive implementation of handling touch input, you could just take the touch point as fact, and the entity would snap directly over to the user’s finger in the scenario described above. This may be visually jarring, which of course may be ok for your game. However, if you want your entity to have more of a realistic presence in the game world, to feel more “real”, the you probably don’t want it teleporting around the screen; At the same time, you want the user’s input not to feel laggy or non-responsive.

So how do we handle this fundamental difference in user input techniques?

The problem of incomplete or inconsistent input reminded me of the network prediction sample, which is available on the XNA Creator’s Club site (http://creators.xna.com/en-US/sample/networkprediction). In that sample, they present two solutions to deal with the issues brought on by network latency. Particularly, I was interested in their smoothing solution because it solves my problem.

Smoothing is a simple concept. When a network packet is received, rather than teleporting immediately to the new position, we can interpolate gradually from the previous position toward this new location, giving the illusion of continuous motion …

I took that smoothing concept and applied it here so that when the user re-touches in another location, the onscreen entity will smoothly accelerate towards his current touch point. And because it’s using interpolation, it will always catch up to the current location after half a second regardless of where the user is moving his finger.

The entity class from the project is listed below. The important bits are the “isCatchingUp” and “currentSmoothing” variables. When the input handling code realizes that it needs to catch up, it starts to decay the “currentSmoothing” variable, which is then used in the interpolation to smoothly transition to the current location (via Vector2.Lerp).

class Entity
{
    private Vector2 lastKnownPosition;
    private Vector2 touchPosition;
    private float currentSmoothing;

    public Vector2 Position;
    public Texture2D Texture;

    public void Update()
    {
        var touches = TouchPanel.GetState();
        float decay = 1f / 15f;

        bool isTouching = touches.Count > 0;
        bool isCatchingUp = currentSmoothing > 0;

        if (isTouching)
        {
            if (isCatchingUp)
            {
                currentSmoothing -= decay;
            }

            foreach (var touch in touches)
            {
                touchPosition = touch.Position;
            }
        }
        else if (!isCatchingUp)
        {
            currentSmoothing = 1;
        }

        if (!isCatchingUp)
        {
            lastKnownPosition = touchPosition;
        }

        Vector2 positionToDraw = lastKnownPosition;
        if (isCatchingUp)
        {
            Vector2.Lerp(
                ref touchPosition,
                ref lastKnownPosition,
                currentSmoothing,
                out positionToDraw);
        }

        this.Position = new Vector2(
            positionToDraw.X - Texture.Width / 2,
            positionToDraw.Y - Texture.Height / 2);
    }
}

Little touches like this add an extra level of polish that players will appreciate … and yes, I intended the pun ;-)

Comments

Enslaving Twitter

I’ve noticed that in recent years, twitter has become the near defacto “engine” for a number of things:

  • Random list data for demos
    Scott Guthrie’s recent MIX keynote demo is a perfect example of this. He uses twitter to populate a simple listbox using his own feed. I do something similar in the sample project for nBayes where I let the user choose two different search terms to populate the two indices from twitter.

    It’s convenient because you don’t have to manage the data set. It’s a bottomless well of perfectly randomized sample data which makes it perfect for this purpose.

  • Using it as a data communication channel
    One of the more interesting usage patterns, the use of Twitter to enable large scale communications and/or data transfer. Jeremy Hilton shows how to use it to manage a voting campaign. Other more “ambiguously practical” projects include TwitterDrive, and even a WCF Communication Channel!

The only unfortunate thing is that whenever I see this stuff used in a demo, they almost always use some xml parsing api to parse out results from the xml API. This can tend to be ugly and error prone. Linq2Twitter seems like an interesting solution because it lets you write  nice strongly typed linq queries and get back the results.

Depending on what you’re doing, having organic sample data can be very useful, there have been many projects attempting to address this in the past. And the use of twitter as a communication channel could be nice because it’s infrastructure you wouldn’t have to manage and maintain (just be prepared to handle fail whales).

Comments

XNA Slides from Orlando CodeCamp 2010

The 2010 Orlando CodeCamp has now come to an end. It was a great event, and I’m glad I was a part of it. Many congratulations go out to Esteban, Will, and the rest of the board and volunteers that put it together. With almost 600 .NET developers in attendance, it shows that the central florida area is brimming with talent.

I’ve uploaded the slides to my presentation which was titled, “How to Finish a Game with XNA“. You can download them here:
XNA_CodeCamp_2010_Slides

If you attended the meeting, please don’t hesitate to contact me if you have a question about XNA, Windows Phone, or any other topic that we spoke about :-)

Comments

Windows Phone 7 Game Archetypes

Now that the .NET landscape has a new “screen” to design for in the form of Windows Phone 7 (WM6.x doesn’t count ;-) ), we need to start thinking about how to provide users with consistent metaphors and input mechanisms.

Microsoft’s patterns and practices group wrote the book on web and desktop application architectures (literally). One of the sections in that book is application archetypes which describes the types of applications that you can build. This is useful because an ecosystem can spring up around each archetype (controls, usability studies, tutorials) which can provide a lot of feedback and guidance for new projects to follow.

To that end I wanted to start a list of the different archetypes that might be available to choose from when designing a game for windows phone 7. Don’t confuse this with a discussion about game genres … those are already well known and documented. This list covers types of applications, game mechanics, and input styles that you can use to directly affect your game’s design in a fundamental way.

  • The Mini-Console
    If you already have a game that you’ve written (using XNA for example) and you want to do a direct port to the phone, then you are writing a Mini-Console game. Games like this will generally be played in landscape mode, which gives the developer enough room to provide a virtual d-pad and button(s) on the bottom left/right of the screen. The idea here is that the user will feel like they are playing a handheld console like the DS or PSP.
  • The ARG
    Alternate Reality Games are growing in popularity. They typified by involving real world elements in one way or another. This can involve using the player’s real world lat-lon location to have in-game effects (using the System.Device.Location namespace), or using the device’s camera as an input mechanism. I don’t see much of these, but it’s an interesting space which I hope more people will investigate.
  • The Physical
    These types of games involve the user physically manipulating either the screen, or the device itself to affect the game play. Games like this have to take this analog data and approximate the user’s intent in making that motion or touch. I often see games which should be mini-consoles try to use this type of physical input just because they can … and it sometimes results in awkward gameplay. More research and testing needs to be done in this space to figure out what works and what doesn’t. For an example of the types of things we should be thinking about, check out my article on approximating touch points.
  • The Casual
    Casual Games are tearing their way through the game industry. Read this report from the recent game developer’s conference for some of that commentary (http://www.designer-notes.com/?p=195). Regardless of which side of that divide you land on, I think one thing everyone can agree on is that casual games are here to stay. WP7′s push notifications and asynchronous game features will be very useful for games like these.

I’d love to keep updating this post with links to more resources on each archetype … if you find something please don’t hesitate to post it as a comment and I will update the post as time goes on :-)

Comments

Approximating Touch Points

The Windows Phone 7 Phone UI Guidelines calls out that the minimum touch target size should be about 9mm (34px) and I started to think about what it would take to implement this in an XNA game. Of course the first thing that comes to mind is that I can define a simple bounding box for each entity that wishes to be touched. This box would have to be of the correct size, and would have to be kept in sync with the entity’s position on the screen. Easy enough I guess.

One of the things that I’ve been thinking a lot about recently is writing software that, instead of strictly defining things can infer a user’s intent. As I pondered the solution above, it occurred to me that defining a bounding box exactly 34 pixels in size was doing just that … limiting the ability for the software to infer the user’s intent in touching the screen. What if his touch point is 35 pixels away from his intended target?

Instead, what if you compare the user’s touch point against the entity positions and simply select the closest one (regardless of whether it’s 35 or 36 pixels away)?

The method below does just that given an array of entities and a touch location:

private static Entity FindNearestEntity(Entity[] entities, ref TouchLocation touch)
{
    Entity selectedEntity = null;
    float currentDistance = 0;

    // The entity with the nearest
    for (int i = 0; i < entities.Length; i++)
    {
        var entity = entities[i];

        float distance = Vector2.DistanceSquared(touch.Position, entity.Position);
        if (distance < currentDistance)
        {
            selectedEntity = entity;
            currentDistance = distance;
        }
    }
    return selectedEntity;
}

This assumes single finger data entry, meaning that it’s probably best served for things like menus and options.

It’s pretty exciting now that XNA has these touch APIs available to it. I am looking forward to doing more research in this space, and playing around with different “natural user interfaces”.

For some great additional resources, be sure to drop by the natural user interface group on the web at: http://nuigroup.com/

Comments (1)

Windows Phone 7 Flashlight

Now that the developer tools for Windows Phone 7 are out in the wild, I wondered how long before we see the ubiquitous “flashlight” app. I decided to grab the bull by the horns and put it out there myself. So find below the steps required to make your own flashlight app

  1. Create a new XNA Game Project for the phone
  2. Add this line of code to the Draw method:
graphics.GraphicsDevice.Clear(Color.White);

And BAM! that’s it!

Comments (4)

Get Googling Orlando!

I’m pretty happy to see the City of Orlando kicking off this effort: http://www.getgoogling.com/

If you are reading this blog and live in the Orlando area, please take a few moments and map yourself and at least fill out the google survey. Then spread the word, it would be pretty awesome to see this come to Orlando :-)

Comments

Of Choppers, Physics, and Challenge

After receiving some sage advice from Andy “The ZMan” Dunn, I posted up the prototype of a game that I am working on for play test on the XNA Creator’s Club site:
http://forums.xna.com/forums/t/49219.aspx

The game focuses on controlling a small 2d chopper through a maze. There are “fans” which push and pull the chopper into the walls which of course will make it more difficult to navigate.

I got the idea after my brother-in-law received a small indoor helicopter for christmas. We all had so much fun trying to carefully control it (as much as one can control those tiny copters) and even trying to land it strange places like the blade of a ceiling fan. I thought that it would be fun to play a game that required the same skill. I was able to fairly quickly make a simple prototype (even simpler than what I posted up for playtest) using the FlatRedBall engine‘s built in acceleration and collision functions.

The prototype I posted up is quite rough around the edges as it is just a prototype; But the idea is to get the community’s feedback early, before you have invested a lot of blood, sweat, and tears into a game. If you wait until the end to get a playtest, you will be so invested in what you’ve been working on that you will resist they playtester’s feedback. I hope to get some good ideas about possible directions that I could take it in … and hopefully it will validate the direction that I’ve already got in my mind. But who knows, I might get an idea that I was not expecting. That’s the great thing about getting it in front of other people early.

We will see just how far along I can get before my Orlando Code Camp presentation, which incidentally, is about actually finishing a game (this game). I’ll definitely have more to post on this topic after the codecamp :-)

Comments