Sections

  • Search Chrome Cow

Design a Day



I’ve collected together all of my various experiments with Flash on this page. Most of what you will find here are snippets of code and small movies that test certain features of Flash, or solve some small, specific problems. There are also a few game-like projects.

Each of the movies posted here also show the source code (or at least the important bits). The goal is to create a resource for other people who are learning Flash, especially ActionScript . All of the exercises below are created in Flash 8. Some of them will work in earlier versions, some will not.

<

 Drawing Regular NGons

Documentation: Palabre 0.6

I am in need of a Flash compatible Socket Server, and found a great open source project, Palabre, with poor docs. This is info gather from docs, forums, etc. [ Link ]


 Drawing Regular NGons

Drawing Regular NGons

I have a project in progress that require me to draw regular NGons (Pentagons, Hexagons, Octagons, etc). I’ve posted the Flash movie and the source code for drawing them, using a simple rotation equation. [ Link ]


Learning Flash

Learning Flash

Since returning from GDC, I have been fired up to learn Flash as a tool for doing some simple gameplay prototyping. It has been rewarding, and at times fairly frustrating, as Flash has some interesting quirks of implementation. It has…personality.

  • Loading Text as Unicode
  • Create and Format a Dynamic Text Field
  • Write-On Text in a Fixed Amount of Time
  • Using Checkboxes
  • The Game Loop

  [ Link ]


Radial Solo Ball

Radial Solo Ball

Flash game number one. Basic goal, build a game with a main execution loop.

First experimentation with collision detection in Flash. [ Link ]


eRadiRace

eRadiRace

A simple wall avoidance game.

First iteration using built-in collision handling in Flash.
[ Failed ]

Second iteration using Flash 8’s Draw API. [ Somewhat Final ]


 


Regular nGons. We’ve all wanted to draw them at some time, right? Look no further, seeker of knowledge, I’ve got just what you’re looking for.

The method I’m using is pretty simple.

  • Assume we are drawing our nGon with its center at 0,0
  • Start with a point at
    • x = 0
    • y = nGon radius
  • for an nGon with n sides
    • rotate the point 360/n degrees
    • do this n+1 times
      • to close the polygon
    • add 360/n degrees each time we iterate

So assume we want a 12 sided nGon. We rotate the first point 30 degrees, the next point 60 degrees, 90 degrees and so on.

For the rotation, I’m using:

x’ = x cos Φ - y sin Φ
y’ = y cos Φ + x sin Φ

Where:
x and y are the original position
x’ and y’ are the new position
Φ is the degree of rotation

And because Flash uses radians instead of degrees, we have to convert from degrees to radians when doing this calculation:

radians = (degrees * Π/180)

Add in an x and y offset to each point to place the polygon in the center of the screen.

Here the code that run the movie:

// Drawing Regular Ngons
// Sean Hyde-Moyer
// April 2007
//
// Initialize variables

xOffset = 350
yOffset = 200
var xArray:Array = new Array();
var yArray:Array = new Array();

vert.text = 5;
radius.text = 120;

this.createEmptyMovieClip("planet_mc", this.getNextHighestDepth());

this.onEnterFrame = function() {
    incrementalRot = 0.0
    updateFlag = 0
    startVerts = Number(vert.text)           
    ngonRadius = Number(radius.text)
   
        //sanity check user values
        if (ngonRadius >180) {
            ngonRadius = 180
            //radius.text = 180;
        }
        if (ngonRadius <= 20) {
            ngonRadius = 20
            //radius.text = 1;
        }

        if (startVerts >512) {
            startVerts = 512
           
        }
        if (startVerts <= 3) {
            startVerts = 3

        }       
   
    // If values change, redraw poly
    if (oldStartVerts != startVerts ){
        updateFlag = 1
    }
    if (oldngonRadius != ngonRadius) {
        updateFlag = 1
    }
    if (updateFlag == 1) {

        degreeRot = 360/startVerts
   
        // Resize the demo circle
       
        circle_mc._height = ngonRadius*2
        circle_mc._width = ngonRadius*2
        circle_mc._x = xOffset
        circle_mc._y = yOffset
   
        // Draw the Ngon
       
        planet_mc.clear()

        planet_mc.lineStyle(1, 0xFFFF00, 100, true, "normal", "square", "miter", 3);
        planet_mc.moveTo(xOffset,ngonRadius+yOffset);
       
        for (i=0; i<=startVerts; ++i) {
            radianRot = (incrementalRot * Math.PI/180)
            xArray[i] = ((0*Math.cos(radianRot)) - (ngonRadius*Math.sin(radianRot)))
            yArray[i] = ((ngonRadius*Math.cos(radianRot)) - (0*Math.sin(radianRot)))
            xArray[i] += xOffset
            yArray[i] += yOffset
            incrementalRot = incrementalRot + degreeRot
            planet_mc.lineTo(xArray[i],yArray[i]);
        }
    }
oldStartVerts = startVerts
oldngonRadius = ngonRadius
}



Since returning from GDC, I have been fired up to learn Flash as a tool for doing some simple gameplay prototyping. It has been rewarding, and at times fairly frustrating, as Flash has some interesting quirks of implementation. It has…personality.

So this is to be a dumping ground for bits and bobs of code and information that I’ve learned, and might help others over some rough spots. No particular order or theme. Just nuggets of Flashy goodness.



Loading Text as Unicode

Use the standard loadVars method:

myLoadVars = new LoadVars( );
myLoadVars.load("unicodeSample.utx");

myLoadVars.onLoad = function (success) {
    if (success) {
        textWindow_txt.text = myLoadVars.quote1;
    } else {
        trace("Load Failed");
    }
}

 

 

The trick is to save the  text out as UTF-8 or UTF-16, with the *.utx file extension. I use JEdit for this, though there are a number of other free unicode text editors available.

Download the Flash File
Flash unicode.fla


Create and Format a Dynamic Text Field

This code creates a dynamic text field, creates a text formatting object, and applies the text format to the newly created text object.

createTextField("display_txt", getNextHighestDepth(), 20, 10, 460, 200);
//createTextField(textObjectName, Zdepth, X, Y, width, height)

my_txt.autoSize = true;
display_txt.text = "Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.";

var my_fmt:TextFormat = new TextFormat();
    my_fmt.font = "Times"
    my_fmt.size = 33;
    my_fmt.bold = false;
    my_fmt.color = 0×0055CC;
    my_fmt.kerning = true;
   

display_txt.selectable = false;
display_txt.antiAliasType = "normal";

this.onEnterFrame = function() { // Update Format Every Frame (for button update)
    display_txt.setTextFormat(my_fmt);
}

Download the Flash File
Flash dynamicText.fla


Write-On Text in a Fixed Amount of Time

This code writes a text string into a dynamic text field, left-to-right, one or more characters at a time, in a fixed amount of time.

This was created for the Design-A-tron, to write-on a text string of arbitrary length, in the amount of time it took to play the gears running animation and sound. It is completely dependent on the framerate of your movie.

var displayMe = "This was created for the Design-A-tron, to write-on a text string of arbitray length, in the amount of time it took to play the gears running animation and sound. It is completely dependent on the framerate of your movie."
displaySize = displayMe.length;

delay = 70;  // The larger, the slower the write on
displayLoop = 0;
endFlag = 0;
displayRate = displaySize/delay;
   
onEnterFrame = function() {  // Runs this loop every frame
   
    if (endFlag == 0) {  // Only Done for Duration of Write-On
   
        // Text Write-On
        tmp = displayMe.substr(0, displayLoop);
        display_txt.text = tmp;
        displayLoop = displayLoop + displayRate;

        if (displayLoop > displaySize) {
            // This writes on the last few characters
            // if the math doesn’t come out right
            // And sets the end condition for the loop
            endFlag = 1;
            display_txt.text = displayMe;
        }
    }
}

 

Download the Flash File
Flash TextWriteOn.fla


How to use freely available images to make the planet of your dreams

A while back, I was called upon to terraform the planet Mars. Having a couple of free hours, I decided to take up the challenge, and turn the red planet blue.

I needed some striking space imagery for pitch material for a proposed space-based MMPO. I’ve spent a fair bit of time tromping around the NASA and USGS (US Geological Survey) websites, glorying at the bounty that our tax dollars make available on the net (see list of links at the end of the tutorial).

The Raw Materials

A cylindrical projection of the Mars surface, taken by one of the planetary surveys done by NASA.

It may seem trivial to be able sit down at your computer and pull up an image like this, but think for a moment at the work it has taken to send these probes, about the size of a Volkswagen Bug, hurtling into space, bouncing through the gravity wells of planet after planet, taking these images and beaming them back to us here on Earth, sometimes taking a decade or more to accomplish the mission. Truly one of the most awe inspiring of human accomplishments.

I’ve scaled down all the images I’ve used in the terraforming project, because I’m paying for bandwidth. The government has great big servers, so go pound on them if you want the full size images…};^) The image below is a sample of the detail you get on these maps. Depending on the use you have in mind, you may need to go through the map with the Photoshop Clone Tool or similar, depending on what software you use, and clean up some glitches and mosaic lines if you think they will show up in your final images. This image was clean enough for my use.

Next on the list was a topographic map (in the same cylindrical projection) of Mars. There are topo maps of Earth, Mars and Venus on the net. There may be a few others, mostly moons. The topographic maps for gas giants are none too interesting.

One of the things that jumps out at you looking at the Mars topo is that at some point in the past, Mars got the crap kicked out of it. In topo maps, white is high, and black is low. The big black spot is where something big hit the planet. But the upper dark band is worse, something enormous hit and pretty much melted half the planet. That’s why there is not much detail, craters, mountains, etc., on that side of Mars. In addition, the other hemisphere was pushed up dramatically. It’s almost like there’s a cliff that circles Mars, delineated by the white/black hemispheres.

Another point of interest is the white spot in the upper left quadrant. This is Olympus Mons, the tallest mountain in the solar system, and a volcano to boot! The mountain is about the size of the state of Arizona, and is about 16 miles (25 Km) high. Almost all the raw materials have been gathered.

All that remains is finding some cloud cover. Novice terraformers might be tempted to use a fractal pattern for cloud cover, but trust me, don’t. Another benefit of the space program; people know what clouds look like from space. There are some good Earth cloud plates floating around on the net, and NOAA (National Oceanic and Atmospheric Administration) takes pictures of Earth’s cloud cover 24/7. Dig around their server for useful images, or make your own.

The plate above is a nice mosaic, though it could be trouble in an animation, since a quick glance detects that it is a hemisphere’s worth of cloud cover cloned (and indeed, many smaller internal features are also cloned. Framed correctly, it is perfect for stills and limited animation.




Understanding (not to mention actually using) Photoshop’s Difference Layer

Over the years, I’ve accumulated a few different uses for Photoshop’s Difference Layer functionality, in much the same way I’ve accumulated old computer parts. I didn’t really go looking, it just sort of happened. My impression is that there are three kinds of Photoshop users: those who’ve never stumbled across Difference, those who have played with Difference and a few who actually use Difference. This how-to should appeal to all three.

What is this Difference You Humans Speak of?

A little bit of simple math up front, then on to the good stuff…I promise. There are a couple of different spots in Photoshop where difference shows up. For the following fooling around, assume that we’re talking about the Difference option that appears in the Layers blending menu.

What does it do? In simplest terms, it compares a layer to the layer just below it. Where the pixels have the same RGB value, it displays black (0-0-0).

Those zeros mean there is no difference between the two layers.

Original Image

Comparison Image

Let’s start with these two images. The original image on the top contains three swatches; 255 red / 255 blue / 255 green. The comparison image adds a stripe of white 255 / 255 / 255 on top, and black 0 / 0 / 0 on the bottom. If we place the comparison image in a layer above the original image and set that layer to Difference, we get this:

So what does that image tell us? Well, let’s start from the bottom. Where the comparison image was black, we see the original colors. What it means is the difference between black, where all the RGB values equal 0, and any other color is the the value of the original color:

In the middle stripe, where the colors are the same, which is to say, no difference, the result is a black strip. The difference between a red pixel and a red pixel is 0, green and green, 0, and so on.

Etc.

The top looks a little funky. What’s the deal? Well, now we have a white stripe, where all the RGB values equal 255. So now we get this:

The astute reader will notice that I’m not being consistent about what layer’s RGB values I’m subtracting, sometimes one, sometimes the other. All we are really interested in is the magnitude of the difference. The equation would actually look something like this:

  • Absolute Value of (Layer_1 Red - Layer_0 Red)
  • Absolute Value of (Layer_1 Green - Layer_0 Green)
  • Absolute Value of (Layer_1 Blue - Layer_0 Blue)

The bottom line: Where the images are the same, you get black. Where they are different, you get something else.




It is by teaching that we teach ourselves, by relating that we observe, by affirming that we examine, by showing that we look, by writing that we think, by pumping that we draw water into the well.

Henri-Frederic Amiel (1821-81)

Use of the following content is governed by the Chrome Cow’s Terms of Service.

Use a Cellphone Camera to Check Remote Control Batteries

Use a Cellphone Camera to Check Remote Control Batteries

Grab some popcorn; there’s a movie. Use you cellphone camera to check the batteries in remote controls in one easy step. Impress your friends and neighbors, win bar-bets. Link


Embrace Difference

Embrace Difference

Photoshop’s baffling Difference Layer; it’s often ignored, or used to ill purpose by those who enjoy its psychedelic flavor. But, honestly it’s not just for rave posters. Peek inside for the story they don’t want you to know. Link


Terraforming for Fun and Profit

Terraforming for Fun and Profit

A vibrant, water cover red planet; the stuff of legends? A multi-trillion dollar investment? Hardly. Using accurate information available for free on the net, add a touch of life to the Red Planet without increasing the budget deficit. Link


Drive on the Wrong Side of the Road

How to Drive on the Wrong Side of the Road

Taking a trip to the mirror-lands where they drive on the wrong side of the road? Here are some helpful hints and strategies for surviving your drive on the wild side. Link