Bacon and Games

Tag: tutorial

How to Simplify Programming Challenges

I recently had a young programmer named Jack (that’s not his butt to the right) ask me for help with a game he’s been working on. I don’t want to give away too much about his unreleased game, but for the sake of discussion I have to at least tell you that it involves a big ass rock that goes around smashing the crap out of different shit. (and 2 sentences in I’ve hit my butt reference limit for this article)

The version he shared with me was pretty far along but he was stuck on one particular detail; getting the rock’s tail to point in the proper direction. Essentially he wanted the tail to point away from the direction the rock was moving, similar to the tail a roll of toilet paper might draw when thrown through the air.

This is a fairly common challenge in game programming and I, like many other game programmers, have done this in the past. I have code that I would have happily handed over to him, but after speaking to him we decided it would be more valuable for me to push him in the right direction rather than just take his FLA and fill in the blanks. I’ll spare you the Chinese proverb about teaching a man to fish..

On Problem Solving
Whether you’re programming super complicated banking software or just making a simple number guessing game, the process is the same.

  1. What do you need to do? Define the challenge.
  2. What do you know? Assess the tools and info you have at your disposal.
  3. Do you have all the pieces? Figure out if what you have can be used to solve the problem.
  4. If yes: Create a plan for using what you have in order to solve the problem.
  5. If no: Break the problem into smaller challenges and return to step 1

This is of course a grotesquely generalized version of problem solving. But what’s important to note is that by asking the right questions you can distill ANY problem into simpler more manageable parts. No matter how complex, the solution to all programming challenges (and most real life ones too!) is simply the sum of smaller problems solved in the right order.

Asking the Right Questions
Let’s take a look at Jack’s problem and how we might break it down into a solution.

1. What do you need to do?
We need to rotate the rock so that it’s “facing” the direction it’s moving.

This is a “plain English” definition of the problem, which is the best place to start, but before we can continue we’ll need to convert the definition of our problem into something we can quantify.

Since movieClips have a rotation (_rotation in AS2) property, it’s likely that we’re going to need to use this to point the clip in the right direction. We know that the rotation property accepts degrees, so we’re probably looking for an angle.

The real answer to Question #1 is:
“We need to figure out the angle at which the rock is moving.”

2. What do you know?
In this step you’ll want to keep the answer to Question #1 in mind, but it’s perfectly fine to be liberal about listing the things you know. You can sort out the relevant data from the irrelevant later, but you never know what piece of information might spark an idea so to start it’s a good idea to list whatever comes to mind. (be creative!)

  • Since the rock is a movieClip we have access to all of its properties; rotation, x, y, etc. These 3 are the most likely to be useful, but remember movieClips have all sorts of properties.
  • It’s moving so we probably know its speed in the x and y directions
  • Our rock might be in an environment with some rules, such as gravity, windspeed and friction. It’s our world, so we’d know all these things too.
  • We also probably know who shot Mr. Burns. Who doesn’t? But I can’t imagine that’s going to do us any good.

3. Do you have all the pieces?
Now that we’ve listed the stuff we know, we have to sift through it for something that might help us calculate an angle.

If we can define a line, we can calculate an angle. Well, a line is defined by two points so let’s look at what we collected in Question #2 and see if we can come up with two points; two points that define the path of our rock.

We have the current location of the rock, via the x and y properties of the movieClip, which would be the end point of our line. We need the starting point to complete the line, which we don’t have in our list.

This means that the answer to Question #3 is “No”. We have to put this part of the problem on hold for now and refine our problem into a more specific question:

Where can we get the starting point so that we can draw a line?

Luckily for us this is an extremely simple problem. On every frame we’re going to be updating the position of the rock. So all we have to do is store the current position of the rock before we move to the next frame. (I recommend a variable called lastPosition)

If we do that, we can add lastPosition to the list of things we know, which gives us two points. We’ve got our line! This means we can calculate an angle, which means we can figure out what angle we need in order to point the rock in the right direction. We’re almost done!

The next thing we need to do is write a function into which we can pass our starting and ending points that will give us an angle in return. Since this isn’t a math lesson, it’s a lesson about learning to fish (OK I lied about the proverb), I’ll just write the function for you. They’re adapted from one of my favorite books, Keith Peters’ Foundation Actionscript 3.0 Animation: Making Things Move! (I’m also a big fan of this book) Both are fantastic resources for math, physics and other common game programming stuff.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// AS2
function getAngle(startX,startY,endX,endY):Number{
	var dx:Number = endX - startX;
	var dy:Number = endY - startY;
	var radians:Number = Math.atan2(dy,dx);
	return radians*180/Math.PI;
}
 
// AS3 
function getAngle(st:Point,end:Point):Number{
	var dx:Number = end.x-st.x;
	var dy:Number = end.y-st.y;
	var radians:Number = Math.atan2(dy,dx);
	return radians*180/Math.PI;
}

The last thing for us to consider is how to setup the rock clip. If we set it up so it’s facing to the right in its default position [rotation=0], the angle we get back from our function will point the rock in the correct direction.

There you have it, a seemingly complex problem broken down into a few manageable parts.

This problem was small, but the process is applicable to a project of any size and challenges of any complexity. The key is accurately defining the things you need to achieve. From there you can survey what you have at your disposal and see if what you have can be used to get what you need. If you can’t, you need to define more specific questions until you have all the tools and info you need to finish the job. It’s just that simple.

Now go, build the next Farmville or twitter or Google Wave, you know…something really useful. Oh, one more thing, bedonkedonk… I lied about the butt thing too ;)

Thanks to Ajay Karat for lending me his rock and fire art for the trajectory sample above.

Learn How to Make Flash Games

If you’re looking to learn how to make a Flash game, Adam ‘Atomic’ Saltsman and Chevy Ray Johnston are coming to your rescue. They’ve recently launched a joint venture, Flash Game Dojo, which is a site dedicated to helping ease people into the world of creating Flash games. Their site aims to answer questions like “How do I add gravity to an object?”, “How do I get keyboard input?” and “Who shot Mr. Burns?”. OK, I made that last one up, plus we all know that it was Maggie. Anyway… Granted the information they’re providing is specific to using their respective frameworks, but a lot of the key concepts and programming models you’ll learn working with Flixel and FlashPunk are still relevant when building a game completely from scratch. And they’re open source frameworks, so if you’re uncomfortable using formulas without deriving them first (remember high school math?), you can open up the guts and see what’s going on under the hood of something as eerily simple as this:

1
2
3
// adding gravity to the player
var player:FlxSprite = new FlxSprite();
player.acceleration.y = 600;

What’s really neat about what Adam and Chevy are doing is that they’re aiming to usher people into the world of creating games. They’re NOT trying to push their respective frameworks, which as products in a marketplace would be competitors. Instead they’ve chosen to offer their work up as free open source options, a space in which they can support each other rather than compete. They’re working together toward a common goal: Get people making great games. I applaud them for that.

I have an upcoming series of articles entitled “Actionscript for Artists” which will focus on providing tools to help artists and programmers work more easily together to make games. It’ll be a mix of code samples, tutorials aimed at teaching artists the basics of Actionscript and tips on how to communicate and collaborate. I come from a more traditional Flash gaming background that uses vector art, movieClips and other techniques more native to Flash, so my focus will be on that style of Flash game development. Flixel and FlashPunk are Flash frameworks that turn Flash into an environment similar to the way old NES games were built, using sprite sheets and raster images. Though our approaches to Flash game development are different, we’re all trying to do the same thing: get people making great games. And besides, variety is a good thing. I’ve only dabbled in Flixel and though it’s a very foreign approach for me (I’m used to building everything on my own, so adhering to a framework is tough for me to get used to) I intend to learn Flixel and FlashPunk. I don’t think I’ll ever abandon the way I’ve always made Flash games, but I do like to try new things, evolve and add new things to my bag of tricks.

Flash Dojo offers a bunch of handy services:

  • A wiki with documentation on both frameworks
  • Q&A style explanations for how to build common game elements
  • Free swf hosting for people who want to quickly test and share a game… likely to be used by people who want to share a work in progress that isn’t ready to go on Newgrounds. You upload a swf and the site gives you a link to share it. It’s that simple. I’ve got webspace coming out of my ears but this is so simple I will undoubtedly use it from time to tim.
  • Articles about game design
  • Software recommendations
  • Tutorials
  • Completed game source for your learning/tinkering pleasure
  • And the bulk of their site’s updates are broadcast via RSS so you can stay abreast of what’s new

If you’re interested in game design I strongly recommend you comb through Flash Game Dojo. Spend some time playing with their frameworks, see what they can do and how they work. But remember that Adam and Chevy don’t have all the answers and they haven’t thought of everything. They will be the first to tell you that their framworks aren’t the ways to build games, they’re just two ways to build games. Learn from what they’ve done, add your own flair and if you think you have found a better way to do something you may well have. I’m sure Adam and Chevy are interested in being the starting point from which people can learn how to make games. What they’re probably NOT interested in is creating a legion of game designers who rely so heavily on Flixel or FlashPunk that the frameworks speak louder than the game experiences created with them. The idea is for people to play your game and remark, “That’s a great game!”, rather than “That’s a great Flixel game!”.

Create. Learn. Play. Question. Invent. Share.

Adam is known for games such as Gravity Hook and Canabalt which he built using the Flixel Framework, for which he is also responsible. Chevy Ray Johnston is behind Flash Punk, another Flash game framework. Both frameworks are designed to handle a lot of the heavy lifting, collision detections, ui, asset management, etc., so that you can focus on game design.

Calculating the Distance from a Point to a Line in AS3

I recently made a game for a client that involved a giant sweeping laser of doom (the game had the laser, not the client). Sounds cool, right? Not if the laser happened to touch you while you were busy blowing up robots. Sound even cooler now that you know there were robots? It was. But that’s not what I want to talk about today. What I’d like to cover is the slightly more exciting topic of how to calculate the distance between a point and a line.

I won’t go into the math behind it, not because it’s complicated but because it’s just not that interesting or important to understand. I’ll just give you the code and then talk a little bit about why it might be useful in a game. If you really want to know how the math works, leave a comment or email me and I’ll do a follow up. For now, here’s a simple visualization (download source here):

This movie requires Flash Player 9

Once again I’ve built on a handy function written by Keith Hair that finds the point of intersection between two lines. Using his lineIntersectLine() function and my getDistanceFromLine() function you can calculate the distance between a point and a line very easily.

Why is this useful? I wrote it so that I could determine if the doom laser had overtaken my hero. Since the laser was represented in my code by two points (a line) and I knew the location of the hero (a point) all I had to do was calculate the hero’s proximity to that line. When the hero’s proximity was less than a certain distance >> kill hero. And because this calculation was done mathematically rather than being tied to a hitTestObject() based on the laser’s movieClip1, adjusting the laser’s killzone was as simple as changing one variable.

Here’s another example of how this information might be useful in a game. Suppose your game has a laser cannon which fires in a straight line, as opposed to the sweeping radar motion in my prior example. If you know each enemy’s proximity to the laser you can apply varying damage and effects to each enemy based on that information.

There are plenty of ways you could use this in a game, but I’ll leave that up to your creativity. You can download the source files for the above demo here. Oh and as is often the case with art in or around my site, the bad-ass laser and art in the screen grab above was done by my partner in crime, Ajay Karat of The Devil’s Garage. He and I are working on some games (not for clients) so expect to see some stuff from us in 2010.

  1. When designing your games you’ll want to keep your visual assets separate from your calculations. Let your calculations dictate what needs to be displayed, not the other way around. Tying calculations to visual assets is usually, if not always, inefficient and inflexible.

User Interface Design Tips for Your Game

A good UI doesn’t require the user to think about how to access or interpret the information and features of your game. What the user needs should be readily available and interacting with it should be intuitive. Every user is different and most of them will not interact with the game exactly as you intended. Making your UI as simple and flexible as possible will allow the UI to fade into the background and help draw the user into the game’s experience. Here are a few things to consider when designing the UI for your game.

Give Users Input Options
Some people are on laptops with small arrow keys. Some people are right handed and some evil people are left handed. Some have a trackpad but no mouse or a keyboard with only one shift key. Giving your users options helps them find a configuration that best suits them. The simplest example is using the arrow keys to move versus using the WADS keys. This is especially true if your game requires simultaneous mouse and keyboard use.

In addition to basic physical comfort, it’s nice to let users decide which actions their dominant hand will be responsible for and which actions will be relegated to that other hand *shudder*. If your game is a simple run/jump platformer, consider letting the user choose between the [arrow keys + Z] -OR- the [WADS keys + L]. You can often get away with leaving both configurations active and not even have to ask the user to select one. This is sometimes the best option because most people will intuitively try the WADS or arrow keys when a game begins and you can safely assume they’ll try their preference first. There’s nothing more comforting than guessing at a game’s controls and finding they’re exactly what you expected them to be.

Give Users Audio Control
There’s no question that audio plays a crucial role in great game design. Anyone who has ever played Left 4 Dead and had their heart jump into their throat when the dreaded tank music kicked in would probably agree [well fuck, I better find some health] . But sometimes sound just isn’t an option for your user (I know I hope people are playing my games while they should be working) and it’s better to have them play the game without sound than to not play it at all. It’s also nice to give users the option of muting just the background music or just the sound effects. Sometimes all I want to hear is Hall & Oates but still want to hear zombies exploding because I’m crazy like that. Same as everything else regarding your UI, don’t make toggling sound a chore. If the game doesn’t use the mouse, don’t make the user click something to toggle the sound and vice-versa for a game that doesn’t use the keyboard. The best approach: allow the user to toggle sound with keystrokes OR a mouse click.

Make Binary Keyboard-Driven Selection as Clear as Possible
Whew, that was a mouthful. Let me ‘splain. No, there is too much. Let me sum up. Early DVD menus that offered wide or fullscreen options on startup were guilty of this. If you have 2 options and are using the keyboard to choose between them, make sure it’s painfully clear which option is selected and which is not. Consider the following scenarios (you will have to click on the Flash object in order for it to receive keyboard input…ironic, I know)

Ambiguous

This movie requires Flash Player 9

Clear

This movie requires Flash Player 9

You don’t ever want your user to wonder which option is currently selected, especially if the options are “continue” and “start over”.

Here are a few remaining thoughts:

  • If you absolutely must have an instruction screen, let your user start your game from there. Do not force them to go back to your main menu just to start the game
  • Programmers love to type dummy text into dynamic text fields at author-time to see how many characters their field will hold. Remember to remove these fillers before you finalize your game. When your game starts showing a score of “00000000000” and then jumps to “5” it’s a jarring transition that doesn’t deserve the user’s attention but will likely grab it.
  • You probably want your games to be so addictive that they evoke that just-one-more-game-I-know-I-can-hurl-that-cat-past-the-barbed-wire replay mentality. So when you create a game that achieves this, make sure you let the user restart as easily and quickly as possible. If it’s a keyboard game, don’t force them to grab the mouse and click. It’s usually best to give them the option to click or press space to restart. If you’ve got their attention, keep them drooling and mashing the keyboard for more :P
  • When designing audio for your game, don’t use headphones. Turn your speakers on and play some music at a reasonable volume. Then design your game’s audio volume within a reasonable range of that. How many times have you opened up a Flash game and been blown away by the game’s music, or conversely been blown away by your own music after quitting the game and resuming iTunes?
  • When displaying large numbers, use commas. 15,389,023 is a lot easier to read than 15389023. I’ve provided a function below that will format a number with commas. I wish I knew who the author is so I could credit him/her. I’ve had it so long (this is converted from AS1) that I don’t recall where I picked it up. Sorry noble mystery coder :(
1
2
3
4
5
6
7
8
9
10
11
12
// adds commas to a number, returns a string for display
public static function addCommas(number:Number):String{
    var numString:String = number.toString();
    var result:String = '';	
    while (numString.length > 3){
        var chunk:String = numString.substr(-3);
        numString = numString.substr(0, numString.length - 3);
        result = ',' + chunk + result;
    }	
if (numString.length > 0) result = numString + result;	      
return result;
}

As I said in 5 Things Flash Game Developers Often Forget, none of these things will make or break a game. But the more little things you get right, the better your game’s overall experience will be.

Intersection of an Ellipse and a Line in AS3

A few months back I was working on a game for which I needed to be able to calculate the points of intersection between a line and an ellipse. I wanted enemies and the hero to be able to collide with and avoid an elliptical obstruction in the middle of the game. I also wanted to be able to calculate whether enemies had a line-of-sight to their targets, given this elliptical obstruction. I did some searching to see if anyone had written a class to handle this. Keith Hair wrote a very nice class that does this with a circle. Aaron Clinger and Mike Creighton wrote a a very nice Ellipse class, but it didn’t deal with ellipse-line intersections, only ellipse-point intersection and general ellipse calculations such as area and circumference. Both of these are great finds, but neither of them did what I was looking for.

Since I couldn’t find what I was looking for I decided I would write it myself and since Aaron and Mike’s Ellipse class had so many useful features I though I’d have my class extend theirs. Here is a demo of my EllipseExt class which has all the bells and whistles of Aaron and Mikes Ellipse class plus some intersection calculation methods added:

This movie requires Flash Player 9

You will notice that by dragging one of the nodes inside the ellipse you lose a point of intersection. However if you switch on the “extend line indefinitely” option the nodes will no longer act as start->end points but rather 2 points that define an infinite line. This is a feature I found helpful for game programming, so I decided to build it in as an optional argument of the getIntersections() method. There is another optional argument that came out thinking about game logic; the sort option. With sort set to true, the getIntersections() method will sort the points by proximity to the first node used to define the line (i.e. the first required argument). This can be very helpful if one of the line’s nodes is a hero or enemy approaching the ellipse and you need to know which of the returned points represents the potential point of impact.

Examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// generic form
public function getIntersections(p1:Point,p2:Point,extend:Boolean=false,sort:Boolean=false):Array
 
// define points that make up our line
var A = new Point(mouseX,mouseY);
var B = new Point(0,0);
// create an ellipse 200x100 at (50,50)
var ellipse:EllipseExt(50,50,200,100);
 
// Example 1:
// find intersections of line AB and ellipse BETWEEN points A and B
var ar:Array = ellipse.getIntersections(A,B);
 
// Example 2:
// find intersections of line AB and ellipse DEFINED BY points A and B
var ar:Array = ellipse.getIntersections(A,B,true);
 
// Example 3:
// find intersections of line AB and ellipse BETWEEN points A and B
// ar[0] will contain the point of intersection that is closest to point A
var ar:Array = ellipse.getIntersections(A,B,false,true);

There are a few other available methods, which I’ll refer to as shortcut methods because each of these can be achieved through the getIntersections method. However, these 4 methods either handle some of the logic you’d otherwise need to build around the getIntersections() method OR they’re acceptably lighter options depending on what you need to know about the line and the ellipse interaction. These are commented further in the EllipseExt class itself, but here’s a preview:

1
2
3
4
5
6
7
8
// simply determines if there is an intersection point at all (line-of-sight)
checkForIntersection(p1:Point,p2:Point):Boolean
// returns the point of intersection between the center of the ellipse and pt
getPointCenterIntersection(pt:Point):Point
// returns points of intersection on the ellipse at the given y coordinate
getInersectionsFromY(y:Number):Array
// returns points of intersection on the ellipse at the given x coordinate
getInersectionsFromX(x:Number):Array

The classes and source code for the above demo can be downloaded here.

I’d like to add some additional methods to this class, specifically for calculating tangent lines/points, which would be useful for pathfinding routes around an ellipse. But I figured that this was far along enough that it was worth sharing. If you have questions or find a bug, please feel free to contact me and I’ll be happy to do what I can to help. I hope you’ll find this useful. Enjoy!

Additional stuff on ellipses for those who need to brush up:
Ellipse Equation Visualizer
Ellipse-Line Intersection
Quadratic Equation

Copyright © 2024 Bacon and Games

Theme by Anders NorenUp ↑