Archive for the ‘Programming’ Category

Pixel Manipulation With AS3

November 21st, 2013 No comments

A bit of code that I developing for creating my level select screen involves manipulating individual pixels from an image. Here’s what my level select screen looks like right now.

Level Selection

To properly explain how I came up with these images, I should explain how I store my maps. I have a standard map sprite sheet that I use for all the levels. Each level map is stored as an array of tiles, with each tile being identified by that tile’s image position on my sprite sheet. Here’s what that sprite sheet looks like.


So what I wanted to do was come up with a color for each tile on the sprite sheet and just use that one color to represent that on the mini-map. I didn’t want to have to recalculate this color every time I changed the sprite sheet, so I created some code to average the RGB values of each sprite. Here’s the code I used to do that.

var tempBitmap:Bitmap = new LevelRegistry.Img_Map1();

for (var y:int = 0; y < tempBitmap.height; y += BaseLevel.yWidth) {
   for (var x:int = 0; x < tempBitmap.width; x += BaseLevel.xWidth) {
      var rValue:Number = 0;
      var gValue:Number = 0;
      var bValue:Number = 0;
      for (var altX:int = 0; altX < BaseLevel.xWidth; altX++) {
         for (var altY:int = 0; altY > 16 & 255;
            var tempPixel = tempBitmap.bitmapData.getPixel(x + altX, y + altY);
            rValue += tempPixel >> 16 & 255;
            gValue += tempPixel >> 8 & 255;
            bValue += tempPixel >> 0 & 255;
      var pixelCount:int = BaseLevel.xWidth * BaseLevel.yWidth;
      var newR:uint = uint(rValue / pixelCount) * 0x10000;
      var newG:uint = uint(gValue / pixelCount) * 0x100;
      var newB:uint = uint(bValue / pixelCount) * 0x1;
      var newColor:uint = 0xff000000 + newR + newG + newB;

So this starts with the upper-left corner of each sprite and then separately totals the R, G and B values. The >> operator is the right shift operator that shifts pixel’s RGB values by 16, 8 or 0 bits. Then the & is a bit-wise “and” operator. Doing an “& 255” gives us only the first 8 bits, which is the total length of individual RGB values in AS3. Then we average the RGB values and add them back together along with 0xff000000 which is a solid alpha channel in flixel. The last step after this is just to read the tile map data and create a new mini-map image for each level.

var output:Bitmap;

for ( var i:int = 1; i <= LevelRegistry.levelCount; i++) {
   if(LevelRegistry["CSV_Map".concat(i)]) {
      var tempMap:String = new LevelRegistry["CSV_Map".concat(i)];
      var rowArray:Array = tempMap.split("n");
      output = new Bitmap(new BitmapData(rowArray[0].split(",").length * 3
             + 2 (rowArray.length - 1) * 3 + 2, true, 0xff000000));
      for (var rowNum:int = 0; rowNum < (rowArray.length - 1); rowNum++) {
         var pixelArray:Array = rowArray[rowNum].split(",");
         for (var colNum:int = 0; colNum < pixelArray.length; colNum++) {
            var currentColor:uint = averageMapColorArray[pixelArray[colNum]];
            var colorArray:BitmapData = 
                  new BitmapData(3, 3, true, currentColor);
            output.bitmapData.copyPixels(colorArray, new Rectangle(0, 0, 3, 3), 
                  new Point(colNum * 3 + 1, rowNum * 3 + 1));
      j = (i - ((i - 1) % 5) - 1) / 5;
      var tempButton:BitmapButton = new BitmapButton(40 + ((i - 1) % 5) * 70, 
            100 + j * 70, 0xff000000, output, this.startGame, i);

One thing to note in this is “LevelRegistry[“CSV_Map”.concat(i)]”. LevelRegistry is my class that stores all the references to level maps, enemy lists, enemy paths, level counts, etc. Calling “ClassName[variableName]” returns a reference to the static variable in ClassName that is named variableName. It’s a nice way to programmatically cycle through a list of static variable names. This way I can add or remove levels to LevelRegistry without having to reprogram the rest of the game.

Categories: Programming, Weekend Tower Defense Tags:

Debug Menu in Flixel

October 29th, 2013 No comments

So for the first feature to review, let’s look at the last one I added, a debug menu.


The textbox on the left displays the details of the current enemy wave list. It’s only there for informational purposes. The one next to it is where the real business is. It can be used to edit and then reset the current wave list. Assuming my towers are already balanced (they’re not), I can use this to tweak the difficulty curve of each level while still in the game. This saves having to re-compile every time I need to update the enemy list for a level.

The other things I can do from this level are remove all the towers from the current level and reset the funds available in the current level. Again, these is used to reset the level state for testing.

The other menus I’d like to add would let me change tower and enemy stats on the fly in order to tweak game balance without having to re-compile. Obviously this menu won’t be in the production release, but it will help immensely during development.

Now, on to the code. My flixel game state is set to a zoom level of 200%. This makes the sprites look a lot better, but text tends to look like crap. My solution is to code all the debug textboxes as regular AS3 textfields overlain on top of the actual game. Here’s the constructor on my DebugMenu class.

public class DebugMenu extends FlxGroup 
public var bgSprite:FlxSprite;
public var waveDisplay:TextField;
public var waveEntry:TextField;
public var moneyText:TextField;
public var resetTowerButton:AltButton; // Custom button class
public var resetWaveButton:AltButton;  // extending FlxSprite
public var setMoneyButton:AltButton;   //

public static var width:int = 400;
public static var height:int = 150;

public function DebugMenu() 
	bgSprite = new FlxSprite(0, 150, null);
	bgSprite.makeGraphic(DebugMenu.width, DebugMenu.height, 0x00cccccc);
	var gfx:Graphics = FlxG.flashGfx;
	gfx.lineStyle(1, 0x000000, 1);			
	gfx.beginFill(0xffffff, 1);
	gfx.drawRoundRect(0, 0, DebugMenu.width - 1, DebugMenu.height - 1, 3);
	bgSprite.dirty = true;
	bgSprite.exists = true;
	waveEntry = new TextField();
	waveEntry.x = 220;
	waveEntry.y = 310;
	waveEntry.width = 200;
	waveEntry.height = 200;
	waveEntry.setTextFormat(new TextFormat(null, 6, 0x000000));
	waveEntry.selectable = true;
	waveEntry.border = true;
	waveEntry.type = TextFieldType.INPUT;
	waveEntry.multiline = true;

        //same as above for waveDisplay and moneyText
	resetTowerButton = new AltButton(215, 185, 0xcccccc, 
              "Reset Towers", 50, 30, this.destroyAllTowers);
	resetTowerButton.label.color = 0x000000;
	resetWaveButton = new AltButton(215, 215, 0xcccccc,
              "Reset Waves", 50, 30, this.resetWaveList);
	resetWaveButton.label.color = 0x000000;
	setMoneyButton = new AltButton(265, 155, 0xcccccc,
              "Set Funds", 50, 30, this.setFunds);
	setMoneyButton.label.color = 0x000000;

As you can see, all the Flixel elements are added directly to DebugMenu, an extension of FlxGroup. This makes it really easy to show or hide them. On the textfields, making them selectable allows copy/paste operations. The type has to be set to TextFieldType.INPUT in order to alter the contents.

Since I’m using a mix of Flixel objects and AS3 objects, I needed to write an additional function to show/hide the debug menu. If I was just using Flixel objects, setting Registry.debugMenu.exists = false; would hide all the elements. Here’s that code:

public function showHide(makeVisible:Boolean):void {
	if (makeVisible) {
		this.exists = true;
		if(!this.waveEntry.stage) {
		if(!this.waveDisplay.stage) {
		if(!this.moneyText.stage) {
	else {
		this.exists = false;
		if(this.waveEntry.stage) {
		if(this.waveDisplay.stage) {
		if(this.moneyText.stage) {
		FlxG.stage.focus = null;

Above is a technique I learned recently that I wish I had known when I was coding this whole thing from scratch in AS3. On a textfield, .stage will be null if the object has not been placed and non-null otherwise. This is the most surefire way to make sure you’re not using .removeChild on an object that hasn’t been placed and that you’re not using .addChild on an object that’s already on the stage.

One last interesting piece of code to deal with textfields in AS3. I thought I could just use .text.split(“n”) to divide the text into an array of lines. Unfortunately, .text removes the new line characters, but using .getRawText().split(“n”); gives you the behavior you want in order to split up the text by line.

In order to get all this stuff working the way I wanted, I needed to rewrite my PlayState class in order to update certain parts of the game when the debug menu is visible, other parts when the game is paused and basically everything when the game is running. I might have shown how I did the last two parts before, but here’s what my PlayState.update() function looks like now.

override public function update():void
	//NUMPADPERIOD is used to show and hide the debug menu
	if (FlxG.keys.justPressed("NUMPADPERIOD")) {
		trace("Toggling Debug Menu");
		this.debugActive = !this.debugActive;

	//Freezes everything once the level is over
	if (gameIsOver) {
		if (FlxG.keys.justPressed("ENTER") ||
				FlxG.keys.justPressed("P")) {
			FlxG.switchState(new MenuState());
	//Only update the debug menu when it's visible
	else if (this.debugActive) {
	//Update the game otherwise
	else {
		//PlayState.update gets run at 30FPS
		//Scaling gameSpeed allows the game to run
		//At 2x/4x speed in order to fast forward the game
		//This is a common tower defense device
		for (var i:int = 0; i < gameSpeed; i++) {
		//Runs things like checking for mouse clicks,
		//button presses and allowing tower placement
		//while the game is paused

So that’s pretty much it for my debug menu. If you’re curious how the AltButton class is set up, I can answer questions in the comments or do a separate post.

Reading Data from a csv file

June 24th, 2013 No comments

I’ve got a working tower data importer for this game. Upgrades are also working and I managed to fix some bugs. Here’s what the game looks like right now.

My tower data is stored in a csv now. CSV stands for comma-separated values. It’s a simple spreadsheet format that gets stored as a text file, which makes it really easy to read. Writing the code to read the file wasn’t hard at all, though I did have some weird issues with Excel. For some reason, the first time I save a file as a csv, Excel saved it as tab-delimited instead of comma-delimited, so it didn’t work at first. Once I updated the csv manually, it worked perfectly. Here’s a sample of my data csv:


So, to explain how I set it up: The first value is the number of towers available. The second and third were just headers for the data below it so I could keep track. The second line is the name of the first tower, followed by the number of levels and the type of bullet it produces. The next row is just headers again so I could actually read the csv without confusing myself. The next 4 rows are the actual data for each level of tower. I include fire rate, which is actually the cooldown between shots, damage, range and cost. Last is the image to use for that level, so that I can change the tower’s appearance as the tower levels up.

And now the code to read the file:

var rawStatsString:String = new TowerStatsCsv;
var currentRow:int = 0;

var rawStatsArray:Array = rawStatsString.split("n");
var rawHeaderArray:Array = rawStatsArray[0].split(",");

for (i = 0; i < rawHeaderArray[0]; i++) {
    currentHeaderArray = rawStatsArray[currentRow].split(",");
    towerStats.push(new Array());
    towerStats[i]['bulletType'] = currentHeaderArray[2];
    towerStats[i]['name'] = currentHeaderArray[0];

    for (j = 0; j < currentHeaderArray[1]; j++) {
        currentRowArray = rawStatsArray[currentRow].split(",");

        towerStats[i][j] = new Array();
        towerStats[i][j]['damage'] = currentRowArray[damageCol];
        towerStats[i][j]['fireRate'] = currentRowArray[fireRateCol];
        towerStats[i][j]['range'] = currentRowArray[rangeCol];
        towerStats[i][j]['cost'] = currentRowArray[costCol];
        towerStats[i][j]['image'] = currentRowArray[imageCol];

Most of this is pretty self-explanatory. First I read the contents of the csv into a string. .split(“n”) splits the string into an array of rows. .split(“,”) gives me an array containing each of the “cell” values of that row.

I’m struggling with what to work on next. I’m definitely thinking I want to get a functional main menu with level select and a save system to track level progress. Definitely thinking about adding some sound back in to the game, but not sure if I want placeholder stuff again, or something that could actually be used for the final game. I’m not sure if I want to add some abilities for the player to use during the game to give the player something else to do. Also considering adding a couple different enemy types and maybe one additional tower type. Any feedback on what I should add next?

Moving Groups of FlxSprites

June 19th, 2013 No comments

Now we’re getting somewhere. I’ve got enemy and tower status menus working. This is about as much as I had before switching to Flixel, so from here on out it’s real progress again. Here’s a video of the current game.

The status menus were a real challenge. In regular AS3, I would just add bunch of different objects to a sprite, and those objects would all move with the sprite. You can’t add objects onto a FlxSprite like a regular AS3 sprite. I thought that maybe I could create a FlxGroup and add all my objects to that and they would all move together, but I was wrong.

Fortunately, FlxGroups were the right way to head. You can iterate over all objects added to a FlxGroup. If you create a baseline FlxSprite that will function as your upper-left corner, you can move that object and then move all the objects in your FlxGroup in relation to that sprite. Here’s the code I used to move my StatusWindow group around:

public function move(point:FlxPoint):void {
    var startPointX:int = this.bgSprite.x;
    var startPointY:int = this.bgSprite.y;

    for (var i:int = 0; i < this.length; i++) {
        this.members[i].x = point.x - startPointX + this.members[i].x;
        this.members[i].y = point.y - startPointY + this.members[i].y;

    this.upgradeButton.label.x = this.upgradeButton.x;
    this.upgradeButton.label.y = this.upgradeButton.y + 3;

Interesting note about that, FlxButtons can be moved using their x and y, but for some reason, the labels don’t move with them and have to be moved separately.

This worked perfectly to move the window to based on a FlxPoint. In order to get the window to follow an enemy as it moves, I had to add a target variable within the StatusWindow class. This tells the window which object to follow around the screen. Unfortunately, x and y coordinates are Numbers (AS3 version of a Float) and they get rounded to an int before being drawn. For some reason, this can cause stuttering when you’re telling one object to follow another. To fix this, I round the x and y coordinates of the followed object before telling StatusWindow to follow it. Here’s the code for that:

public function findBestLocation():FlxPoint {
    return new FlxPoint(Math.round( - 50), Math.round( - 70));

This function will later be used to keep the window on the screen, without flowing onto the menus or off the edge of the screen. For now, it just offsets the location of the target object.

Oh, and I almost forgot that I added win and loss conditions to the level. You can see at the end of the video that a little text appears. It says, “You win!!! Press enter to return to menu.” That’ll have to get changed at some point, but it works. There’s also a loss condition when your invisible health drops to 0 that also directs you to return to the menu. They both switch a gameIsOver Bool to true in my PlayState. This causes the game to skip the update loop and instead checks to see if the user is pressing enter to return to the menu. Here’s the top of the PlayState’s update code now:

override public function update():void
    if (gameIsOver) {
        if (FlxG.keys.justPressed("ENTER") ||
                FlxG.keys.justPressed("P")) {
            FlxG.switchState(new MenuState());
    else {
        for (var i:int = 0; i < gameSpeed; i++) {

I’ll be adding the rest of the stats to the bottom menu, along with actual buttons to press to change game speed. Then I think I’ll export my tower stats to a csv file or something and make the game import the stats. That will make it easier to balance the game later. While setting that up, I’m going to add an ability to declare several levels for each tower so they can be upgraded.

Overriding Inherited Functions in Flixel

June 12th, 2013 No comments

I now have working tower select buttons on the side menu and the ability to pause, unpause and speed up the game working again. In order to get these abilities working, I had to override Flixel’s default update() function on PlayState (an extention of FlxState). Things can get messy real quick when changing those inherited functions, so I’ll share some of the issues I ran in to, but first, here’s a video of the game’s current status.

First of all, when I override the update() function for a FlxSprite, I’m usually trying to add behavior without removing the default behavior. To do this, I start with this basic function override:

override public function update():void

    //Add new code here

All this does is override the inherited update() function, with a new function that calls super.update() (the inherited version of update). You can then add any additional code as needed.

My favorite addition this iteration is the ability to speed up and slow down the game. I did this by rewriting PlayState’s update() function to this:

override public function update():void
    for (var i:int = 0; i < gameSpeed; i++) {

This was a really simple way to add this feature. It just runs the update code as many times as needed per frame in order to reach the requested speed. Note: if gameSpeed is 0 or less, the update function won’t be run at all, effectively pausing the game.

Now, for anyone that’s played a standard Tower Defense game, you’ll know that you usually want to place some towers before the enemies start coming. To do this, the game should start in a “paused” state and then let you “unpause” to start the enemy waves. If you haven’t played a Tower Defense game, think of it like the Sims. You go into build mode to add your furniture so that the Sims aren’t getting in your way while you place things. Having this pause function lets you do that.

Unfortunately, I placed the code that enables you to press buttons and that let’s your currently selected tower follow your mouse into the TowerMenu.update() and Tower.update() functions respectively. Those functions are called from FlxState’s update function. And when gameSpeed is set to 0, FlxState’s update function is never called. To make matters worse, the code that tells the towers to fire is located in Tower.update(). So if I just call that function while the game is paused, the towers would keep firing.

My solution was to move those pieces of code directly into the PlayState class. Since the code only affect one specific object (the currently selected Tower) and not every Tower object, it’s okay to take that code out of the Tower class. So here’s my new PlayState.update() function:

override public function update():void
    for (var i:int = 0; i < gameSpeed; i++) {

public function runNonGameUpdates():void
    var tileWidth:int = Registry.currentLevel.xWidth;
    var tileHeight:int = Registry.currentLevel.yWidth;
    if(this.activeTower !== null) {
	this.activeTower.x = FlxG.mouse.x - FlxG.mouse.x % tileWidth;
	this.activeTower.y = FlxG.mouse.y - FlxG.mouse.y % tileHeight;
	if (FlxG.mouse.justReleased()) {
            this.activeTower.placed = true;
	    this.activeTower = null;

That Registry.towerMenu.checkMenuButtons() is where the code checks if menu buttons are being pressed. Flixel doesn’t have a function to check if a FlxSprite was just clicked, so what I did was add code that would get checked when FlxG.mouse.justPressed() is true and again when FlxG.mouse.justReleased() is true. When pressing the mouse, the code checks to see if your mouse is on top of a button and then sets that as the active button. When the mouse is once again released, it checks to make sure your mouse is on top of the same button. If it is, the button’s clicked function is activated. Afterwards, regardless of whether a button was “clicked” the active button is cleared out. Here’s what the code looks like:

public function mouseButton():int {
    var i:int;

    for (i = 0; i < TowerMenu.buttonCount; i++) {
        if (FlxG.mouse.x >= TowerMenu.startX
                && FlxG.mouse.x <= (TowerMenu.startX + buttonWidth)
                && FlxG.mouse.y >= (TowerMenu.startY + 
                    (buttonHeight + buttonGap) * i)
                && FlxG.mouse.y <= (TowerMenu.startY + 
                    buttonHeight  * (i + 1) + buttonGap * i)) {
            return i;
    return -1;

public function checkMenuButtons():void
    if (FlxG.mouse.justPressed()) {
        TowerMenu.buttonPushed = this.mouseButton();

    if (FlxG.mouse.justReleased()) {
        if (TowerMenu.buttonPushed == this.mouseButton() 
                && TowerMenu.buttonPushed >= 0) {
        TowerMenu.buttonPushed = -1;

So now that I’ve got this code working, it’s time to add the bottom menu that tracks current funds, health, waves remaining and some victory/loss conditions. I think that will bring me back to where I was before I switched to Flixel. So far, it’s been a lot easier using Flixel. I’ll definitely be using it for any future game jams, because it makes prototyping a lot easier.

Decompilers Good, Hibernating Bad

February 11th, 2012 No comments

So I haven’t done any work at all on my game since last weekend. Mostly because losing a week’s worth of work on it was depressing me. I believe I’ve found a way to fix it, but it’s still a pain in the butt.

Hibernation Fail
Here’s what happened. I loaded up my computer on Tuesday night to start doing some coding. FlashDevelop was open when the computer put itself into hibernation due to a low battery. I pulled it up to see this:

FlashDevelop post hibernation

There might not appear to be anything wrong with that at first. The only problem is that when I shut down my computer on Saturday night, I had about 14 classes and there’s only 6 in that picture. I figured, “Well, that just must be because that’s what I had open.” So I browse to the folder where I had been saving all my files. Which I had been saving regularly. And what did I see? 7 files with the last modified date listed as 1/29/2012. Even though I had been working on my code as recently as 2/4/2012.

Looking For The cause
Now I can’t say for sure that it was the hibernation file that caused the issue. I don’t see how loading the contents of RAM should affect a folder full of files saved on the hard drive. I suppose it’s possible that “Saving” was only occurring in FlashDevelop’s memory, but that seems unlikely.

The odd part about it all, was that the compiled swf file – the one that’s created every time I try to debug the game – was still showing a last modified date of 2/4/2012. I loaded it up and, lo and behold, it was the same file I had pulled screenshots from last Saturday.

I still don’t know for sure what happened. But I’ve turned off all hibernation on the laptop just in case. I really don’t mind shutting it down every night when I’m done working. It forces me to save more often anyways.

Finding a Fix
I did try downloading a trial for a deleted files recovery tool. But it acted as if the files had never existed as well. I knew about the importance of securing your code before releasing it into the public. This is because it’s supposed to be really easy to decompile unencrypted flash files. I figured I would look for a decompiler and see what my finished swf file could give me.

I can tell you to NOT try sothink’s swf decompiler. It will let you see your code, but the local variable names will be changed and you can only copy out the code if you buy the full version.

I knew there had to be a free decompiler out there, so I googled “free actionscript 3 decompiler” and was led to F.L.A.S.W.F.. He had links to several decompilers and the one I decided to try was ASDec. Looking at the output I was surprised to find that every variable name is identical to the original version.

My Code Is Reborn!

The decompiler isn’t perfect though. It still has to leave out all the comments because those aren’t compiled at all. It also has many extra lines added in declaring variables and then initializing them on separate lines. Fortunately, it should recompile fine for now and I can update it as I go. I was really concerned for a couple days, but I’m ready to return to coding my game once again.

I’ve learned to appreciate decompilers, so long as they aren’t used to steal my game and pass it off as someone else’s. Anyone else every have computer nightmares resulting in lost code?

Move Engine Recompleted

February 4th, 2012 1 comment

Once again I can move my units as I desire. Next is the reprogramming of the AI. For now, enjoy this screenshot of the movement area, recreated.

3 Steps Forward, 2 Steps Back

Well, time to tuck into bed for the night. While it’s disappointing that I haven’t gotten back to where I was 2 weeks ago, I think I’ll be much happier with the code once it’s done. Just about every variable is private now and the classes are properly encapsulated.

Doctor Who and Programming Time

February 3rd, 2012 No comments

I just found that my local library has the first two seasons of Doctor Who available on DVD. I watched the third season a few months ago and loved it and thought it was the only season they had. I’m wide awake and ready for some programming. I think I’ve got one more class to program and the game will be functioning again.

So it’s 9:30 and I’m settling down in front of my desk with season 1 of the new Doctor Who and FlashDevelop to finish my game prototype. Screenshots to follow later tonight, maybe even a video.

Programming A Click and Drag Function

February 3rd, 2012 No comments

Last night I decided to program in a function to allow easier map scrolling when using mouse controls. Previously I had made it similar to the Wii’s turning functionality in first-person shooters. When you got near the edge of the screen, the game would start to scroll in that direction.

The problems arose when you were just trying to access buttons that were off screen because the game would try to scroll in the direction of the buttons. It was just too easy to accidentally scroll. And if you wanted to scroll to the other side of the screen from where you were, you needed to move your mouse all the way to the other side.

Enter Click and Drag
So last night, I decided I was going to make my game scroll when I clicked and dragged. This was a more intuitive interface, similar to the iPhone’s scrolling functionality.

My first attempt at setting this up had mixed results. The scrolling was jittery and it wasn’t 1:1 for some reason. Check out my code below to see if you can spot the error. For reference, the mouseDown function is called when the user presses the left mouse button while on the map, the mouseUp function is called when the user releases the left mouse button while on the map and the mouseMove function is called when the user moves the mouse around the playField, but only after the mouse button is pressed.

private function mouseDown(e:MouseEvent):void {
	this.startMouseX = this.mouseX;
	this.startMouseY = this.mouseY;
	this.startX = this.x;
	this.startY = this.y;
	this.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
	this.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
	Main.stageSprite.addEventListener(Event.DEACTIVATE, mouseUp);		

private function mouseUp(e:Event):void {
	this.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
	this.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
	Main.stageSprite.removeEventListener(Event.DEACTIVATE, mouseUp);	

private function mouseMove(e:Event):void {
	this.x = (this.startX - this.startMouseX + this.mouseX);
	this.y = (this.startY - this.startMouseY + this.mouseY);

Ignore the fact that the game will keep scrolling if you happen to release the mouse button while your mouse is outside the flash screen. I haven’t yet figured out how to fix that, so anyone that has a solution should let me know. If you can spot the other error in my code, then you’re a better programmer than I was last night.

The Solution
The problem, it turned out, was caused by my use of this.mouseX and this.mouseY. You see, as you move a sprite around, it’s mouseX and mouseY coordinates change to reflect the relative position of the mouse from the sprite’s (0,0) point, usually the upper-left hand corner.

What was happening was the game would update the mouse coordinates at the same time it tried to update the map’s coordinates. Resulting in what some would call hilarity, but what I called annoyance. To fix the problem, all I had to do was update the references to this.mouseX and this.mouseY to Main.stageSprite.mouseX and Main.stageSprite.mouseY.

Main is my initializing class and stageSprite is a static reference to a sprite that never moves. So as the map scrolled around, the stageSprite stays where it is and provides an accurate reference point to calculate how far the mouse has moved. Here are the results:

Starting Position

The ending point after one click and drag

So overall, I’m pretty happy with the results. I’m trying to reintegrate my old classes for moving units around and attacking other units now. The only problem is that I changed many of the variable names for my units and actually implemented private variables instead of public variables, so I have a lot of updates left to make before I can even run the game without compiler errors. Maybe I just need to program those classes from scratch too. As I write this I’m buzzing from my 2nd coffee this week (I only drink coffee 2-3 times per week to avoid developing a tolerance) and I’m probably feeling way too ambitious. Maybe that’s for the best.

Programming Part-Time

January 31st, 2012 2 comments

So I know I haven’t made much visible progress on my game since I started this blog. And I think it’s due in large part to working on it part time.

Since going back to work after the new year, I haven’t had a normal sleep schedule. I got used to staying up until 2 AM every night instead of my typical 11 PM. I’m finally starting to get back to my “normal” schedule. But until now, this terminal sleepiness has made programming after work difficult.

This is a situation a lot people get into when they start trying to start up a business or project on the side. A full-time job can be really draining and after one and a half hours of commuting and eight and a half hours at work, the last thing on anyone’s mind is putting in work on a side project. The only thing keeping me working on my game is my intense passion for games in general and my strong desire to turn this into a career.

While I don’t expect to quit my job and start developing flash games full-time in the near future, releasing and selling my first game is the first step towards that goal.

Even if I produce a mediocre game that sells for $50 after I put a couple hundred hours into it, it’s still worth it. If I want a career in video games, having released one will help. If I want to turn this into a business, having released a game is necessary. Even if all I do with this is use the experience to improve my programming skills, it’s worth it.

So I’m resolving to get this game finished and ready for sponsorship on Flash Game License by May 1 of this year. If I have to rush the last bit and release a game that’s barely more than a prototype, I’ll do it. Stay tuned over the next 3 months to follow my progress. You’ll know as I get closer to the deadline whether I’m going to release a crappy game or something actually worthy of playing.

Let me know what you think of my goal in the comments. Is it not ambitious enough? Too ambitious? Should I instead follow the advice of this article on Lifehacker and schedule some time each week to work on my game?