2D Tile Maps – Tile Picking

Several months ago, I talked about the distinction between world space and screen space. As a recap, these are fundamental concepts that separate our game or simulation state from our drawn or rendered state. What gets drawn to the screen is not necessarily how things are laid out in the game’s actual (world) state. Check out the previous articles for more information.

The concept of tile picking involves a user hovering their mouse or some other input device over a tile in the game map. Usually the user is doing this in order to interact with the tile such as moving a unit to a location, placing an item on the tile, or inspecting the metadata of the tile. Fortunately for the developer, the process of picking is independent of the projection other than some simple math to do a conversion of coordinates.

Imagine that you are playing SimCity 2000, and you want to create a stretch of road from one location to another. The process involves the user hovering the starting tile, clicking the mouse, dragging the road to the end tile, and releasing the mouse. Tiles were picked out of the game map based on the mouse’s coordinates during game updates. Which space do we pick the tile from? Do we have to calculate if the mouse is contained within the projected tile or within the game’s world space coordinates?

Orthogonal

If the projection used in the game is orthogonal (think NES/SNES Zelda games), then the tile picking really is just a matter of answering the question, “Which tile contains the current mouse coordinate?” Answering the question is simple:

To explain briefly, we get the position of the mouse (I use SDL which has a function to get the mouse position). We then convert the coordinates from screen space into world space. Finally we get the tile that is stored in our tile collection at the world space coordinates. We floor the coordinate conversion because landing in the middle of a tile will result in a partial index.

worldspaceReference the grid to the left. For the sake of discussion, let us assume that each grid contains 16 x 16 tiles. The top left most pixel is located in world space [0,0] and at screen space (0,0). The top right most pixel is located in world space [5, 0] and at screen space (80,0).

If the user moves the mouse to the screen space coordinate (25, 50), then the math to calculate the picked tile is as follows (using the aforementioned technique).

worldspacetilepickPerforming that calculation, we get a result of the tile highlighted in blue.… Read more

2D Tile Maps – World and Screen Spaces

If you are not familiar with tile maps, please see the previous article in this series before reading this article.

Spaaaaaaace!

A space is simply some collection of points, vectors, shapes, and other objects that we use to store the state of our game or simulation. There are various kinds of spaces that can be employed during game development, but the two that I will focus on for this article are the concepts of world spaces and screen spaces. It is important to know the distinction and differences between these two spaces because it will make your game development journey much clearer and easier. Personally, it took me awhile before the concept of separating the spaces really “clicked” for me.

World Space

The most commonly understood space is the world space of the game. This is the space that contains the positions of all entities in the game. For example, if we have a 5 x 5 tile map where each tile is 16 x 16, worldspacewe can represent that map (as discovered in the previous article) as a two dimensional array where [0, 0] is the first tile and [5, 5] is the last tile. Where these tiles are drawn on screen is of no importance when you generate the tile indices in the representative array. The underlying world of your game is represented by this array. The entities live their lives in this boring, mundane, grid-like existence.

All the game interactions and logic take place within this world space because of how extremely simple and efficient it is to perform calculations if we assume our game is as simple as an evenly laid out grid. But when we plays most tile based games, we notice immediately that what we interact with certainly is not as boring as the pictured world space to the left This should make sense to you after thinking about it for a little bit. Think of games like SimCity, Diablo II, or The Legend of Zelda. Even though each of these games has different views and projections, they can still be represented by a very simple tiled world space.

Screen Space

So what about those various projections then? If games that rely on tiles are nothing more than glorified arrays, how do games get those pseudo 3D effects complete with movement, collisions detection, and tile selections with the mouse? This is where the screen space comes in to play. The screen space is nothing more than a visual representation (via rendering) of the underlying world space in which our entities live.

Remember when I said that isometric and oblique projections share the same data structure? I said it because they do! The world space for both projections is identical. Only when you look at their screen spaces do things begin to diverge. By performing the previously discussed transforms to our world space, we can end up with a nice looking screen space in which the player will act and react. In fact, the player does not even know or care about the world space!… Read more

2D Tile Maps – An Introduction

Tiles and You!

So maybe you have or have not heard about tiles within the context of video games. For those of you who have, great, tread onwards into the more advanced areas of the article. But to those of you who have not, take some time to let the information below soak in. I strongly suggest that you spend time implementing and testing some solutions of your own in throwaway projects just to see the results in real time and for yourself. Many people are hands on learners and doing a lot of the experimentation yourself goes a long way to understanding the concepts.

I plan to make a few articles about various topics in tiles, tile maps, rendering, and interacting. Part 1 will focus on the concepts behind two popular formats of tile maps and rendering techniques. Part 2 will delve more deeply into rendering isometric tile maps with an explanation of the differences between world space and screen space. Finally, in Part 3, I will discuss topics such as isometric tile picking and moving entities within an isometric tile space.

Before all that though, let’s begin with the basics, shall we?

Cartesian Tile Maps

Maps are often stored and displayed in equally sized tiles to make life easier on the renderer and the artists. It is usually easier to begin understanding a tile map in an oblique projection, which is one of the simplest (but very effective) forms of projecting your tiles. Many popular games from the 80s, 90s, and even 00s take advantage of this projection due to its relatively simple mathematics.iGpPx For example, in the Legend of Zelda on SNES, tiles were utilized to create structured maps with the ability to quickly re-use art assets and build customizable terrains. Notice how the bushes, rocks, fence posts, and walls can be evenly split into tiles of equal sizes? Can you see how this tile map could easily be stored in a data structure such as an array?

cartmapImagine storing a tile map in a two dimensional (or even one dimensional with some cleverness) array. Each cell of the tile map represents one index into the array with the origin most commonly being [0, 0]. Since each tile has a specific width and height (usually equal, but does not have to be), it is quite simple to render this map by simply using multiplication.

You can think of this as simply drawing your array to the screen with a specific texture based on the position.… Read more

Read about My Game: The Chains of Acadia

I have been developing software professionally for about 5 years now, and I have been playing video games nearly my entire life. The combination of the two is something that I decided to tackle back in July of this year. Having never programmed for anything other than enterprise software, I decided to ease my way into the scene via XNA. I was already familiar with C# through my work, so it was an obvious choice to learn the basics and dip my toes into the ocean of game design.

Since I am a full-time employee, I usually only get nights and weekends to work on this project. I would love to dedicate all my time to the development of my first game, but I am constantly reminded that something has to pay the bills. Anyway, you did not come here to read about my life; you came to read about my game! I have quickly learned that game development calls for many different talents. Some of the requirements include skills that I simply do not possess. Namely, I have trouble producing quality art, sound, and music. Since I am in this alone (for now), I have to rely on the wonderful open source community to fill this important gap. I can handle the technical side no problem, but when it comes to art, yikes. Without further ado, here is my game.

The Chains of Acadia is a story of a hero. Oh, wow, how original. The thing is though, Acadia (the hero), does not know that he is a hero. When he finds out the truth, he probably will not want the status bestowed upon him. I do not want to ruin the story, so I will stop there and simply explain the style of play involved. The best way to describe the style is to picture Smash TV mixed with a slight bit of Touhou and some minor RPG elements.

Take this image from my Twitter account for example. You can see that the player is constricted on four sides by the walls of the screen. Not every screen will have this type of layout, but it will be the most common. The player has to complete several waves and challenges to proceed to the next screen. Remember in Zelda dungeons when going through a door would slide the camera to the next screen? This is similar.

Screens (maps) will make up a larger “level” that the player can explore to complete challenges, events, and puzzles. Unlike Smash TV, I want the player to have to return to certain screens for one reason or another. Maybe to pick up an item that was not available the first time around. Maybe there is a locked door that can only be opened by pushing a button or retrieving a key in another map. In order to add some fun to the mix, I have implemented a system that generates bullet patterns reminiscent of the Touhou series of games. This allows me to create some really cool challenges that the player must navigate through while attempting to destroy waves of enemies, defeat boss battles, or complete puzzles.… Read more

Resolution Independent 2D Rendering in XNA 4

When I first started making my game, I hard coded the screen resolution to 800 x 600 for simplicity and built my menus and levels with the assumption that the screen was exactly 800 pixels wide and 600 pixels high. This was a mistake because all of my UI positions, tile positions, and entity placements were based on absolute positions and did not look proper when the resolution changed. If the user wanted to use a screen size that was not 4:3 and super tiny, the game looked completely wrong and was unplayable because the level layout was all over the place.

To solve this, I used David Amador’s Resolution class to introduce a means of rendering my scenes independent of the actual resolution of the window. I maintained an “internal” or “virtual” resolution of 1280 x 720 (Xbox standard) to be used for position of all my entities and UI elements. This virtual resolution never changes. Users can then adjust the “actual” resolution of the game which determines the real window size. We use a scaling matrix to transform the virtual resolution to fill the actual resolution with additional letterboxes or pillarboxes depending on the virtual and actual resolutions. I suggest you read the linked article from David Amador to understand the class and how to use it.

Changes for XNA 4

David’s article is what really counts when it comes making this work. However, it was written pre-XNA 4 and requires a minor change. Calls to SpriteBatch.Begin() require more parameters in the overload that allows for a transform matrix. The current method of using David’s code to scale your virtual resolution up to the actual resolution is:

Obviously, your needs will dictate the exact parameters, but this is the overload you need to use at the very basic level.

Transforming Mouse Coordinates

Another problem you’ll run into is when trying to use mouse coordinates to interact with the elements of your game. The transformation matrix is applied only to the sprite rendering and does not affect the state of the mouse cursor. For example, using a straight up MouseState.GetState() will return coordinates in terms of the actual resolution and not the virtual resolution. Since your game is working in terms of the virtual resolution, this behavior is wrong!

Luckily, one of the commentors in David’s article explained a way to transform mouse coordinates into the virtual screen space. Here is a simple static abstraction that I created to get mouse position in terms of virtual resolution.

First, add two static members to the Resolution class.

Second, assign values in the ResetViewport() method.

On Game Input and Response (Mouse, Keyboard, and Controller)

The Importance of Input

One of the large distinctions between video games and other forms of entertainment is the ability for the user to provide input to directly affect the state of the system. In essence, the user is driving the medium and has direct leverage over the future of their character(s) within the rules of the system. This uniqueness places a large burden on the designers to provide a good system of input for the users. Such a system can be the difference between maintaining loyal users and being completed ignored or negatively criticized.

When users play games, not much is worse than delayed/confusing controls or input with very little visual or aural feedback to indicate action occurrence and consequence. Think about that for a second. Try to think about how we manipulate the world in our actual lives. When you lift a book, open a page, or slide something across a table, action and response is immediate. Unfortunately, manipulating in a game system is never 100% immediate because there are levels of abstraction between you and the electrons. However, a designer can certainly work around this annoyance to provide a smooth experience. There are several considerations to maintain in order to achieve good input and feedback, and it is slightly dependent on the control schema available. (mouse, controller, headset, etc…)

Mouse and Keyboard

On the PC, the mouse and keyboard are kings. There are other ways of controlling your computer through touch interfaces, headsets, speech, and USB controllers, but the majority of the time is spent using a mouse and keyboard. In my personal opinion two of the largest sins regarding mouse input is the application of mouse acceleration and the occurrence of “soupy” mouse movement. The former is a large point of debate and the latter is a consequence of bad design and possibly video settings.

Mouse acceleration is the acceleration of the mouse cursor as you move your mouse at variable velocities. Moving the mouse from one corner of your mouse pad to another at a crawl will move the cursor on the screen a smaller distance than if you jerked the mouse across the mouse pad. This is because the mouse acceleration is trying to help with precision pointing at small velocities and reduce physical movement at large velocities. Honestly, I can see where it  might be helpful for some scenarios, but when it comes to games, I hate the inconsistent mouse movement that is a result of the acceleration kicking in. When I play games like Counter-Strike, reliable mouse movement is huge. “Flickshotting” where the user jerks the mouse from one point to another for a quick AWP kill is more difficult to achieve when mouse acceleration is on due to the variable velocity. No one will move from point A to point B on their mouse pad with the exact same velocity every time. Because of that, the actual translation of the mouse on the screen will fluctuate. Maybe this is not as important for slower games, but I still want the translation of my physical mouse to match up with the translation of the cursor regardless of the speed at which I am operating.… Read more

Build XNA Game Installer: Visual Studio Setup Project

This guide assumes:

  • Visual Studio 2010 Professional
  • XNA Game Studio 4.0
  • Users will be Windows

This is the second article about building an XNA game installer when you are ready to distribute your game to the masses. In the first part, I described how to use the convenient ClickOnce option to build a relatively simple and non-customizable deployment package. If the ClickOnce option is too restrictive for you or simply does not meet your needs then you should refer to this article about using a Setup Project to create a more customizable installation package.

As with most things in life, the Setup Project is not a perfect solution to packaging up and distributing your game. What I find extremely annoying and shortsighted on Microsoft’s part is that the Setup Project will not automatically detect your game content like ClickOnce does. I want to be clear that, in this context, “content” is referring to your compiled content by the Content Pipeline (textures, sounds, other files) and not the “content” of your project as a whole. I will explain how to force the Setup Project to use your game content. Be warned: it is tedious and annoying, but it works..

  1. Open your game solution
  2. Right click solution -> Add -> New Project…
  3. Other Project Types -> Setup and Deployment -> Visual Studio Installer -> Setup Project
  4. Right click the setup project -> Properties
  5. Change the “Configuration” drop down to whatever configuration you want the setup to use (debug/release/etc)
  6. Click “prerequisites”
  7. Make sure these are checked:
    • Microsoft .NET Framework 4 Client Profile (x86 and x64)
    • Microsoft XNA Framework Redistributable 4.0
    • Windows Installer 3.1
  8. Right click the setup project -> View -> File System
  9. In the “Application Folder”, right click -> Add -> Project Output
  10. Change the “Project” drop down to the main game project
  11. Click “Primary” output in the list box
  12. Choose the configuration for which you want to include the output (debug/release/etc)
  13. Repeat steps 9-12 for any other projects that you need to include in the output (custom libraries)
    • NOTE: Do note include output from content pipeline extension projects because the content pipeline it is unavailable at run time

You just created a setup project, told it which prerequisites are needed for your game to work, and finally told it which build output you want to include in the installer. You can arrange the “File System” folders to how you see fit for your application folder hierarchy. For example, you should see options to include files in the User’s Desktop or the User’s Programs Menu in case you want to include shortcuts. Be careful not to abuse this though, because the user will not be happy if you dump 500 files on their desktop!

While that was relatively painless, all is not well in setup project land. For some reason there is no way to have the setup project automatically find your compiled content in .xnb format after the content pipeline has imported and processed your content files. You can include the “Project Output” of the content project, but that will not do anything useful, so do not bother!… Read more

Build XNA Game Installer: ClickOnce

This guide assumes:

  • Visual Studio 2010 Professional
  • XNA Game Studio 4.0
  • Users will be Windows

This article is the first of two on how to package your XNA game into an installer for Windows environments. The first is the easier but less customizable option of using Visual Studio’s built in ClickOnce installer. ClickOnce is essentially a hand-holding tool to package up prerequisites, dependencies, manifests, and content. Additionally, it allows you to specify locations from which the users will install the package (CD, Web, Shared Drive). More conveniently, ClickOnce allows you to specify where the application should check for updates in order to automatically update the content when new versions of the application are released. For example, you could specify a URL that the application will use to check for new versions. If a new version is detected, you can specify either the same URL or a different URL to use for downloading the new content.

While ClickOnce is easy to use, it is not perfect for every scenario and can fail quite spectacularly. I have personally run into situations where users could not install updates to the application because of cryptic errors that were only resolved by completely recreating a user account in Windows (I kid you not, this is a Microsoft-sanctioned approach). Many of the errors are difficult to diagnose and the documentation does not help much when it comes to the more advanced features of ClickOnce. It is definitely convenient, but do not use it if you want customization or extendability.

That said, here is how you use ClickOnce to package your XNA game into an installer.

  1. Open your solution in Visual Studio
  2. Right click your main project -> Properties…
  3. Click Publish tab
    • Publishing Folder: local or remote path that will be the destination of the publish (example: C:DevGamesGame1Installer)
    • Installation Folder URL: optional unless you want the users to install from a location different from the publish location
    • Install Mode: Pick offline availability (users should not have to be connected to the internet to play video games!)
    • Click Application Files…
      • Make sure the Publish Status of your game files is set to Include (Auto)
      • Make sure the Publish Status of the XNA libraries is set to Prerequisite (Auto)
    • Click Prerequisites…
      • Microsoft .NET Framework 4 Client Profile
      • Microsoft XNA Framework Redistributable 4.0
      • Windows Installer 3.1
    • Click Updates…
      • Check for updates if you want your application to check for updates through ClickOnce
      • A lot of the options are self explanatory on this screen
    • Click Options…
      • Description tab
        • Publisher name: your company name
        • Suite name: optional used to define a super application that manages this one
        • Product name: the name of your game
      • Deployment tab
        • If you want to deploy to a web page, specify the URL here
        • Check the other options here if need them
      • Manifests
        • Click “Create desktop shortcut” if you want a shortcut
        • Ignore the other options unless you really need them
  4. Specify the version of this publish (you can have it auto increment if you want)
  5. Click either the Publish wizard (which just confirms your already entered information) or Publish Now to begin publish

Your published files will be organized like this:

  • Application Files
    • Contains every version that has been published (in case user needs to rollback to a previous version)
    • Contains “Content” folder which includes files from your Content project in your XNA solution
    • .dll libraries that you created
    • Game icon
    • Game thumbnail
    • ClickOnce application file used to check for updates
    • Game executable
    • Executable manifest
  • ClickOnce application file used to check for updates
  • Setup.exe used to install the game

Note that the Application Files directory will contain a history of every version of your application.… Read more