Flash Cove http://flashcove.net Quality AS2 and AS3 Flash Tutorials! Thu, 23 Jun 2011 21:06:19 +0000 en hourly 1 http://wordpress.org/?v=3.1.1 Flash Historical Stock Chart Tutorial (Yahoo Data) http://flashcove.net/834/flash-historical-stock-chart-tutorial-yahoo-data/ http://flashcove.net/834/flash-historical-stock-chart-tutorial-yahoo-data/#comments Thu, 23 Jun 2011 21:06:19 +0000 Dave http://flashcove.net/?p=834 Flash Historical Stock Chart Tutorial (Yahoo Data)

  I like investing in and following the stock market. I also like developing in Adobe Flash. What a great flash tutorial idea to develop a stock application! What I...

]]>
Flash Historical Stock Chart Tutorial (Yahoo Data)

 

I like investing in and following the stock market. I also like developing in Adobe Flash. What a great flash tutorial idea to develop a stock application! What I have got for everyone here today is an interactive chart in Flash that dynamically grabs stock prices and other data from the Yahoo finance feed , parses, and then displays historical prices for any stock from it’s IPO (initial public offering) to present day. Additionally, because of sandbox security restrictions, your flash player cannot access external sites such as yahoo.com, only items on the same hosting server. To bypass this security restriction, a couple of php proxys were also written and stored on my server, which act as middlemen for the flash application to grab ticker information from Yahoo icharts.


The entire application is a couple hundred lines of code, but on the positive side, this is a pure actionscript 3 application, so no actual Flash IDE functionality,  external movieclips, etc.. was needed! Directly below is the source code for the tutorial in addition to a LIVE, WORKING demo of the stock chart! Enjoy this great Flash and Actionscript 3 tutorial, from the one and only, flash cove tutorial site!

Place both the flash file and two php scripts (BE SURE TO CHANGE FORMATTING FROM .TXT TO .PHP!) in the same directory/folder, and then run the “stock_chart.fla”



Here’s the final yahoo finance based stock graph, in a compiled flash program, for your enjoyment:

You can trace the historical stock prices anywhere on the flash chart by tracing along with your mouse. I defaulted with the big blue chip Microsoft (MSFT), but you can search any stock listed on the market by typing it up in the top right corner, such as AAPL for Apple Inc, CSCO for Cisco, CMG for Chipotle, F for FORD, YHOO for Yahoo, ONTY for Oncothyreon (which, with Stimuvax, is a great stock right now), etc..., and then pressing enter. Enjoy!

With that, lets get to work on the actual flash tutorial for this sweet stock application.

 

Since there is a lot of code for this flash stock chart tutorial, I am only going to go over the actionscript source code in high detail. It is up to you to decipher the smaller facets within. I’ve lined the code with a few comments to help you identify where certain objects are laid out and created, but feel free to leave a comment below if you need any help or want to post some suggestions to me or others on the flash cove.

With that, let’s get to the actual development for this flash tutorial:

INITIALIZATION

var arr:Array;
var max:Number;
var max_volume:Number;
var increment_level:Number;
var titleLoader:URLLoader;
var input_field:TextField = new TextField();
var stock_line:Sprite;
var volume_array:Array;
var year_array:Array;
var top_left:Point = new Point(15,40);
var dimensions:Point = new Point(800,300);

var displayed_data:Array = new Array();

This first part is pretty easy, we are just initializing some global variables in flash for our stock chart to use.

  • An array to stock price numbers and data
  • variables for max stock price and maximum volume
  • for every pixel on the chart, how many days we advance in the price history (that’s our increment_level)
  • titleLoader is our download wrapper for obtaining the tickers company name
  • input_field is where we can type in new stock tickers to search
  • stock_line is the actual stock price line on the screen, a flash sprite
  • volume_array is the series of lines at the bottom of the stock chart indicating volume; all sprite lines.
  • year_array are all the little text values indicating years on the bottom of the stock price chart (from IPO to current)
  • top_left is a point marking where our chart begins on the screen
  • dimensions obviously mark the width and height we want for the chart. This is scalable to whatever you like
  • displayed_data is storage for our formatting setups

And with that, let’s get to a little bit more initialization. Some actual sprites and graphics on the flash screen.

//initialization of all the little labels and formatting for the stock chart

var current_stock:String = "MSFT";

var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x333333);
square.graphics.beginFill(0x111111);
square.graphics.drawRect(top_left.x,top_left.y,dimensions.x,dimensions.y);
square.graphics.endFill();

square.addEventListener(MouseEvent.MOUSE_MOVE, show_popup);

var volume_square:Sprite = new Sprite();
addChild(volume_square);
volume_square.graphics.lineStyle(3,0x333333);
volume_square.graphics.beginFill(0x111111);
volume_square.graphics.drawRect(top_left.x,top_left.y + dimensions.y + 22,dimensions.x,dimensions.y/6);
volume_square.graphics.endFill();

square.addEventListener(MouseEvent.MOUSE_MOVE, show_popup);


var tracer:MovieClip = new MovieClip();
tracer.graphics.lineStyle(1,0x222222);
tracer.graphics.beginFill(0xffcc00);
tracer.graphics.drawCircle(0,0,3);
square.addChild(tracer);
tracer.graphics.endFill();
tracer.visible = false;

var tracer_line:MovieClip = new MovieClip();
tracer_line.graphics.lineStyle(1,0xFFE87C);
tracer_line.graphics.moveTo(0,top_left.y);
tracer_line.graphics.lineTo(0,top_left.y+dimensions.y);
square.addChild(tracer_line);
tracer_line.visible = false;

var tracer_price:MovieClip = new MovieClip();
tracer_price.graphics.lineStyle(1,0x817339);
tracer_price.graphics.beginFill(0x111111);
tracer_price.graphics.drawRoundRect(-40,top_left.y - 5,80,12,10,10);
tracer_price.graphics.endFill();

var price_field:TextField = new TextField();
price_field.type = TextFieldType.DYNAMIC;
price_field.border = false;
price_field.x = -40;
price_field.y = top_left.y - 8;
price_field.selectable = false;
price_field.height = 16;
price_field.width = 80;
price_field.multiline = false;
price_field.wordWrap = false;
price_field.background = false;
price_field.text = "MSFT";

var price_format:TextFormat = new TextFormat();
price_format.color = 0xFDD017;
price_format.size = 8;
price_format.font = "Verdana";
price_format.align = TextFormatAlign.CENTER;
tracer_price.addChild(price_field);
price_field.setTextFormat(price_format);

stage.addChild(tracer_price);
tracer_price.visible = false;

var tracer_date:MovieClip = new MovieClip();
tracer_date.graphics.lineStyle(1,0x817339);
tracer_date.graphics.beginFill(0x111111);
tracer_date.graphics.drawRoundRect(-50,top_left.y + dimensions.y - 5,100,12,10,10);
tracer_date.graphics.endFill();

var date_field:TextField = new TextField();
date_field.type = TextFieldType.DYNAMIC;
date_field.border = false;
date_field.x = -40;
date_field.y = top_left.y - 8 + dimensions.y;
date_field.selectable = false;
date_field.height = 16;
date_field.width = 80;
date_field.multiline = false;
date_field.wordWrap = false;
date_field.background = false;
date_field.text = "MSFT";

var date_format:TextFormat = new TextFormat();
date_format.color = 0xFDD017;
date_format.size = 12;
date_format.font = "Verdana";
date_format.align = TextFormatAlign.CENTER;
tracer_date.addChild(date_field);
date_field.setTextFormat(date_format);

stage.addChild(tracer_date);
tracer_date.visible = false;

All this scary looking stuff is just the box where our stock line goes, the box where the volume lines go down below, and then the vertical tracer line that shows a specific stock price and the date it is recorded for. We initialize colors, sizes, and positions, and then add the necessary event listeners that go along with each element in the flash tutorial.

The next part of learning for this flash stock tutorial, is the event listener for ourpopup / tracer linethat we initialized in the previous chunk of actionscript code above.

POP-UP/TRACER EVENT LISTENER:

function show_popup(e:MouseEvent):void{ //these are the two little ovals that follow our vertical tracer line
    if(mouseX < top_left.x + dimensions.x && mouseX > top_left.x){
        tracer.visible = true;
        tracer.x = mouseX;
        tracer_line.visible = true;
        tracer_line.x = mouseX;
        tracer_price.visible = true;
        tracer_price.x = mouseX;
        tracer_date.visible = true;
        tracer_date.x = mouseX;
   
        var possib_y:Number = (top_left.y + dimensions.y) - ((arr[Math.floor((dimensions.x - (mouseX - top_left.x))*increment_level)][4] / max)*dimensions.y);
        price_field.text = "$"+arr[Math.floor((dimensions.x - (mouseX - top_left.x))*increment_level)][4].toString();
        date_field.text = arr[Math.floor((dimensions.x - (mouseX - top_left.x))*increment_level)][0].toString();
       
        var price_format:TextFormat = new TextFormat();
        price_format.color = 0xFDD017;
        price_format.size = 12;
        price_format.font = "Verdana";
        price_format.align = TextFormatAlign.CENTER;
        tracer_price.addChild(price_field);
        price_field.setTextFormat(price_format);
        date_field.setTextFormat(price_format);
       
        tracer.y = possib_y;
    }
}

If the mouse position is within our specified stock chart range, update the positioning for our tracer popup and all related data. Every time the tracer is updated, we also need to reflect that in the text formatting for the stock price. That’s the code you see at the bottom of this function.

The next chunk of actionscript code, which is our largest and most complex, is the initial construction of the stock chart and graphs. We make a request to my php script on the flashcove.net server, it in turn makes a request to the yahoo finance servers, gets a file back called “table.csv“, and then that is fed back in to flash via a return variable to the URLLoader function. Once that data is safe in our hands, we parse through, find price and volume maximums, break the dates in to meaningful chunks, and display on-screen.

CHART CONSTRUCTION:

var csvLoader:URLLoader = new URLLoader();
csvLoader.dataFormat = URLLoaderDataFormat.TEXT;
csvLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{ trace(e); }); //error listening, just in case
csvLoader.load(new URLRequest("http://flashcove.net/wp-content/get_stock.php?url="+current_stock));
csvLoader.addEventListener(Event.COMPLETE,CSVLoaded);

function CSVLoaded(e:Event):void {
    var str:String = csvLoader.data as String;
    arr = str.split("\n"); //break it up
    arr[1] = arr[1].split(',');
    max = Number(arr[1][4]);
    max_volume = Number(arr[1][5]); //find our max volume and price to set a perspective scale
    for (var i:int=2; i<arr.length; i++) {
        arr[i] = arr[i].split(',');
        if(Number(arr[i][4]) > max){ max = Number(arr[i][4]); }
        if(Number(arr[i][5]) > max_volume){ max_volume = Number(arr[i][5]); }
    }

    //get the line ready!
    stock_line = new Sprite();
    stock_line.mouseEnabled = false;
    square.addChild(stock_line);
    stock_line.graphics.lineStyle(3,0x817339);
   
    //secondary lining for the stock price, makes it look cool
    var dropShadow:DropShadowFilter = new DropShadowFilter();
    dropShadow.distance = 2;
    dropShadow.angle = 45;
    dropShadow.color = 0xFFE87C;
    dropShadow.alpha = 1.0;
    dropShadow.blurX = 1;
    dropShadow.blurY = 1;
    dropShadow.strength = 1;
    dropShadow.quality = 15;
    dropShadow.inner = false;
    dropShadow.knockout = false;
    dropShadow.hideObject = false;  
    stock_line.filters = new Array(dropShadow);
   

   
    stock_line.graphics.moveTo((top_left.x+dimensions.x), (top_left.y + dimensions.y) - ((arr[1][4] / max)*dimensions.y));
   
   
    volume_array = new Array();
    year_array = new Array();
    increment_level = ((arr.length-1)/dimensions.x);
    var prev_item:int = int(arr[1][0].substring(0,4));
    var first_year:int = int(arr[arr.length-2][0].substring(0,4));
    for (var k:int=2; k < dimensions.x; k++) {
        if(int(arr[Math.floor(k*increment_level)][0].substring(0,4)) < prev_item){// && int(arr[Math.floor(k*increment_level)][0].substring(0,4)) > first_year){
            add_text("\'"+prev_item.toString().substring(2,4),50,(top_left.x+dimensions.x) - k - 8, top_left.y + dimensions.y + 4,8);
            //year line
            var year_line:Sprite = new Sprite();
            year_line.mouseEnabled = false;
            square.addChild(year_line);
            year_line.graphics.lineStyle(1,0xECD872,0.1);
            year_line.graphics.moveTo((top_left.x+dimensions.x) - k, (top_left.y + dimensions.y));
            year_line.graphics.lineTo((top_left.x+dimensions.x) - k, top_left.y);
            year_array.push(year_line);
        }
        prev_item = int(arr[Math.floor(k*increment_level)][0].substring(0,4));
       
        stock_line.graphics.lineTo((top_left.x+dimensions.x) - k, (top_left.y + dimensions.y) - ((arr[Math.floor(k*increment_level)][4] / max)*dimensions.y));
       
        //volume
        var volume_line:Sprite = new Sprite();
        volume_line.mouseEnabled = false;
        volume_square.addChild(volume_line);
        volume_line.graphics.lineStyle(1,0x817339);
        volume_line.graphics.moveTo((top_left.x+k), (top_left.y + dimensions.y) + 22 + (dimensions.y/6));
        volume_line.graphics.lineTo((top_left.x+k), ((top_left.y + dimensions.y) + 22 + (dimensions.y/6)) - ((arr[Math.floor(k*increment_level)][5] / max_volume)*(dimensions.y/6)));
        volume_array.push(volume_line);
    }
   
    //High-Low-Current prices
    add_text(max.toString(),50,top_left.x + dimensions.x + 4, top_left.y - 2,12);
    add_text("0",50,top_left.x + dimensions.x + 4, top_left.y + dimensions.y-2,12);
    add_text(arr[1][4].toString(),50,top_left.x + dimensions.x + 4, (top_left.y + dimensions.y) - ((arr[1][4] / max)*dimensions.y),12);
   
    //Input Box!
    input_field.type = TextFieldType.INPUT;
    input_field.border = true;
    input_field.x = top_left.x + 228 + dimensions.x - 350;
    input_field.y = top_left.y - 26;
    input_field.height = 16;
    input_field.width = 88;
    input_field.maxChars = 6;
    input_field.scrollH = 0;
    input_field.multiline = false;
    input_field.wordWrap = false;
    input_field.background = true;
    input_field.backgroundColor = 0x111111;
    input_field.borderColor = 0x333333;
    input_field.text = current_stock;
   
   
    input_field.addEventListener(KeyboardEvent.KEY_DOWN,new_stock_handler);
   
    var input_format:TextFormat = new TextFormat();
    input_format.color = 0xFDD017;
    input_format.size = 16;

    input_format.font = "Silkscreen";
    addChild(input_field);
    input_field.setTextFormat(input_format);
    input_field.embedFonts = true;
    input_field.antiAliasType = "advanced";
   
   
    add_text("Search New Ticker Symbol: ",200,top_left.x + dimensions.x - 350, top_left.y - 24,16);
   
    square.swapChildren(tracer,stock_line);
   
   
    //Plop on the company name / title
    titleLoader = new URLLoader();
    titleLoader.dataFormat = URLLoaderDataFormat.TEXT;
    titleLoader.load(new URLRequest("http://flashcove.net/wp-content/get_stock_name.php?url="+current_stock));
    titleLoader.addEventListener(Event.COMPLETE,grab_company_name);
   
}

The first for loop iterates over the received data, and stores it in to an array. We then setup our line display values (such as the drop shadow and thickness), and move the line sprite into starting position. Inside the second for loop, we actually draw a line segment between the current stock price and the next, creating the graph as we go along. If we see the beginning of a new year in the data, write down the date at the bottom of the graph and draw a thin gray line to represent it. Additionally, each time we add a little chunk to the stock history graph, we also draw a volume line down in the tiny box on the bottom to show volume history.

Just a few more bits to go, first we display the high, low, and current stock prices on the right-hand side of the stock chart, which you see changes every time I search a new stock on the flash demo. We also create the input box so that our users can search for more stock symbols. And finally, make a request to the yahoo finance servers again to grab the company’s name given that we already know the stock ticker (Either the initial “MSFT” or whatever a user types in the search bar)!

Three more functions to go!

COMPANY NAME FUNCTION:

function grab_company_name(e:Event):void{
    var str:String = titleLoader.data as String;
    var company:Array = str.split("\n");
    company[0] = company[0].split(',');
    company[0][0] = company[0][0].substring(1, company[0][0].length-2);
    add_text(company[0][0].toString(),200,top_left.x, top_left.y - 24,16);
}

Very similar to the function we used to grab stock price history before. Split the input file on newlines, and then grab the company name off the first data entry in the 2D array. Call “add_text” to create the actual instance on-screen in flash.

Next function, ADD TEXT HELPER:

function add_text(mess:String, wid:Number, xpos:Number, ypos:Number, font_size:Number):void{
//Creating the textfield object and naming it "myTextField"
var myTextField:TextField = new TextField();

//Here we add the new textfield instance to the stage with addchild()
addChild(myTextField);

//content, width, x, and y coordinates.
myTextField.text = mess;
myTextField.width = wid;
myTextField.x = xpos;
myTextField.y = ypos - 5;

//Here are some great properties to define, first one is to make sure the text is not selectable, and also disabling the border.
myTextField.selectable = false;
myTextField.border = false;

//textfield autosizes with the text, aligning to the left.
myTextField.autoSize = TextFieldAutoSize.LEFT;

// create a TextFormat instance
var myFormat:TextFormat = new TextFormat();

//format a hex decimal color code
myFormat.color = 0xECD872;

//set the text size
myFormat.size = font_size;

//set font.
myFormat.font = "Verdana";

//the MOST important thing, actually apply the formatting
myTextField.setTextFormat(myFormat);
displayed_data.push(myTextField);
}

This is a helper function we’ve used several times throughout the program. Rather than creating a full instance and construction for each and every text entity on screen, we can just make this one helper function and call IT repeatedly instead! It takes, as input, the text, width, x and y positioning, and font size. We could have made it a little more dynamic with font colors and such, but that wasn’t really necessary for this simple flash tutorial.

The only real peculiar thing here is the displayed_data.push(myTextField);. That line exists, because, when we switch to a new stock chart, all the old information needs to be removed from the previous stock. Rather than blindly search for the instances on the screen, it is super easy to just iterate through the displayed_data array, remove from screen, and then delete the data!

Which is exactly what’s shown in the last and final actionscript function.

NEW STOCK HANDLER:

// get key press only when the stock textfield is being edited
function new_stock_handler(event:KeyboardEvent){
   // if the key is ENTER
   if(event.charCode == 13){
       //clear out the stock price line
       stock_line.graphics.clear();
       for(var ff:int = 0; ff < displayed_data.length; ff++){
           removeChild(displayed_data[ff]);
       }
       displayed_data.splice(0,displayed_data.length);
       
       //clear out all the volume bars
       for(var gg:int = 0; gg < volume_array.length; gg++){
           volume_square.removeChild(volume_array[gg]);
           volume_array[gg] = null;
       }
       volume_array.splice(0,volume_array.length);
       
       //clear out all the year bars
       for(var hh:int = 0; hh < year_array.length; hh++){
           square.removeChild(year_array[hh]);
           year_array[hh] = null;
       }
       year_array.splice(0,year_array.length);
       
       current_stock = input_field.text;
        csvLoader = new URLLoader();
        csvLoader.dataFormat = URLLoaderDataFormat.TEXT;
        csvLoader.load(new URLRequest("http://flashcove.net/wp-content/get_stock.php?url="+input_field.text));
        csvLoader.addEventListener(Event.COMPLETE,CSVLoaded);
   }
}

This function checks for the “ENTER” strike form the input text box, and if it’s there, deletes everything currently onscreen, and restarts the stock chart initialization function with a new request for data from the Yahoo finance servers!



And that’s it for the actionscript code! Of course it’s a couple hundred lines long, and in some cases confusing and unclear, but if you need any help, first look at the actual compiled code in your own flash IDE, and then follow up with any questions in the comments section if you need clarification.

All that’s left now is the two PHP files we accessed in the actionscript code above, at the web addresses:

  • “http://flashcove.net/wp-content/get_stock.php?url=”+input_field.text
  • “http://flashcove.net/wp-content/get_stock_name.php?url=”+current_stock
  • “http://flashcove.net/wp-content/get_stock.php?url=”+current_stock

What exactly are these PHP files and what are they doing? It’s not voodoo magic, but at first it may be hard to understand, especially if you don’t have a lot of web experience.

There’s certain security restrictions within flash, and to prevent harmful things from happening to your computer, eternal data access can only happen on the same local PC as where the flash file resides. Since the stock information is hosted on yahoo.com servers, and not on my flashcove.net server, security restrictions prevent me from accessing stock information online.

HOWEVER, if I instead didn’t use flash to request yahoo’s finance data, and rather a PHP file on my own server, there would be no such restriction. This is exactly what I did. The get_stock.php file will grab stock information, and temporarily cache it on my flashcove.net server. Flash can then access that cached info locally, and use it to display some charts.

When we call the PHP file from inside flash, we can dynamically pass parameters via appending ?variable1=variabledata1&variable2=variabledata2&variable3=variabledata3&… to the PHP file call.
All we append though in this flash tutorial is the ticker title for the specific stock.

With that, let’s look at the get_stock.php contents:

<?php  $filename = $_GET["url"];
 $filename = "http://ichart.finance.yahoo.com/table.csv?s=$filename";
 header("Content-Type: text/csv; Content-Disposition:attachment; filename=\"$filename\"");
 readfile($filename);
?>

We grab the passed in ticker symbol from the “url” parameter, append it to the yahoo finance webserver call through the $filename variable, and then actually call readfile to execute the file transfer. This will automatically feed the response back in to the URLLoader event listener in flash, which can then be parsed for the graph.

The other PHP file we use, get_stock_name.php, is just a call to acquire the company name for display above the graph. It’s file structure is very similar to the get_stock.php setup.

<?php  $filename = $_GET["url"];
 $filename = "http://finance.yahoo.com/d/quotes.csv?s=$filename&f=n";
 header("Content-Type: text/csv; Content-Disposition:attachment; filename=\"$filename\"");
  readfile($filename);
?>

The only thing that changed was the yahoo request URL, and we also added “&f=n” to specify we want a COMPANY NAME returned (Hence the “n“).

You now have everything you need to turn this stock flash tutorial into your very own dream stock application. My specific flash demo is riddled with bugs, doesn’t handle a ticker that doesn’t exist, and also has many other small, annoying, issues. You could really make this a professional application just like the one Google or Yahoo Finance uses for their charts. With selectable date ranges, variation on sizes, zoom, intraday stock prices, EVERYTHING. I’ll probably come around again sometime and make a more polished version of this tutorial, but for now this is plenty of ammunition for your own projects.

Just remember that, if you’re going to create your own online or commercial version of this flash stock chart application, to update the URLs of the PHP files! You don’t want to be pinging mine, but rather your own. It’ll be faster and you won’t have a dependency on someone elses servers, only your own.

Thanks everyone for tuning in, and I wish you the best of luck on your own projects and endeavors in flash and the stock and finance world!

- Dave at the Flash Cove (http://flashcove.net)

]]>
http://flashcove.net/834/flash-historical-stock-chart-tutorial-yahoo-data/feed/ 0
Cubic Spline Generation in AS3 – Catmull Rom Curves http://flashcove.net/795/cubic-spline-generation-in-as3-catmull-rom-curves/ http://flashcove.net/795/cubic-spline-generation-in-as3-catmull-rom-curves/#comments Thu, 26 May 2011 16:20:38 +0000 Dave http://flashcove.net/?p=795 Cubic Spline Generation in AS3 – Catmull Rom Curves

   While mathematically complex ( at least compared to all the other tutorials on this site ), curve generation techniques such as these catmull rom splines are absolutely critical in...

]]>
Cubic Spline Generation in AS3 – Catmull Rom Curves

  
While mathematically complex ( at least compared to all the other tutorials on this site ), curve generation techniques such as these catmull rom splines are absolutely critical in the design of games, movies, and media. This specific flash tutorial on spline curve generation only covers 2D creations, but can easily be mapped to a 3D environment, which I will show in another, later tutorial. There is so much power in the knowledge of how to create these splines; in fact, the Pen tool itself in Adobe flash uses similar spline curve creation on it’s back-end implementation (Bezier, not catmull). Here’s a list of some of the practical applications for curve creation using catmull rom splines.

  • General Path interpolation (both 2D and 3D curve mapping)
  • Most blockbuster animated movies ( Pixar, Dreamworks, etc.. ) use catmull rom splines for camera path animations
  • Surface clamping, ex: map a roller-coaster to a track, car to a sloped road, …
  • Combined with a frenet frame, we can get interpolation across a position AND orientation ( something like a full roller coaster simulation, where the camera follows orientation of the track too ).
  • 3D graphics rendering, still-frame and animated
  • Design of a car body; engineers use splines to model and create the smooth shape of a commercial car’s body (Honda, Ford, Toyota cars, etc..)

I hope you can see this has a wide application of uses. So, with that, here’s our source code and demo!

Place the flash file somewhere on the hard drive, and then run “catmull.fla” using CTRL+ENTER inside the Flash IDE.

Here’s the final flash catmull rom dynamic curve example, for your enjoyment:

Click and drag the white circles to observe the dynamic curves in flash, they will move and bend at the user's command!

So lets start development on this curve generating flash tutorial!

  1. Create a new flash document, standard size, 550 pixels by 400 pixels, actionscript 3 (AS3). Set the background color of the stage to a dark color ( mine is 0×003333 ).
  2. Head up to the top, Insert -> New Symbol, Movieclip, name it “ball“, and check the “Export for Actionscript” box. Make sure the class name is “Ball” with a capital B.  Once inside, draw a simple circle to represent your markers that are going to be used for the drag and drop anchors in flash. Make sure they are centered about the orientation cross!
  3. Now that we’ve got the ball in place, all we need to do is write up some quality actionscript 3 code ( about 120 lines! ) But before we do this in Flash, let’s get a quick explanation on how catmull rom actually works..

Using a series of control points, we can procedurally generate spline segments between the points.  As seen in the picture on the right, we use 4 control points and a desired t along the curve to create a new point. We can do this for many different values between t = 0 and t  = 1.  In this flash tutorial, we build 200 segments between each pair of control points, by starting t = 0, and incrementing each time by 0.005 in a for loop, up to t = 1.  The easiest way to ensure we have four control points at all times is to loop back from the last to first control point at the end. Sometimes, developers will either fabricate additional control points that are not visible, or use a “Blended Parabolas” technique to tie off the ends of the interpolation path.

The equation we are using to find sub spline points between P1 and P2 is this:

Where y is the result vector, t is the parameter (between 0 and 1) and the x’s are the grid vectors. In other words, we have 4 points, x1…x4 and we’re trying to interpolate smoothly between the middle two, x2 and x3. At t=0, the above equation evaluates to y = x2, and at t=1, it evaluates to x3. Intermediate values give the points in-between we are trying to find.

With that, let’s get to the actionscript 3 development for this spline curve flash tutorial!

Flash initialization and the Catmull Rom actionscript 3 function:

var lineDrawing:MovieClip;

var Spline_Points:Array = new Array();
var Spline_Lengths:Array = new Array();

var Interpolation_Points:Array = new Array(new Point(100,100),new Point(50,200),new Point(450,250),new Point(100,300));

//CATMULL ROM FUNCTIONALITY
function calculate_catmull(t:Number, p0:Number, p1:Number, p2:Number, p3:Number):Array{
    var t2:Number = t*t;
    var t3:Number = t2 * t;
    // P(t)
    var firstn:Number = (0.5 *( (2 * p1) + (-p0 + p2) * t +(2*p0 - 5*p1 + 4*p2 - p3) * t2 +(-p0 + 3*p1- 3*p2 + p3) * t3));
    // P'(t)
    var secondn:Number = 0.5 * (-p0 + p2) + t * (2*p0 - 5*p1 + 4*p2 - p3) + t2 * 1.5 * (-p0 + 3*p1 - 3*p2 + p3);
    // P''(t)
    var thirdn:Number = (2*p0 - 5*p1 + 4*p2 - p3) + t * 3.0 * (-p0 + 3*p1 - 3*p2 + p3);

    var arr:Array = new Array(firstn, secondn, thirdn);
    return arr;
}
//END CATMULL ROM FUNCTIONALITY

We create an “Interpolation_Points” array, and initialize some points we can to draw. The calculate catmull function does exactly what the mathematical equation above represents. Multiply out the matrix against the control points, get our primary function, the first and second derivatives, and return.

Next piece of the code, Drawing the Markers:

function draw_anchors():void{
    for(var k:Number = 0; k < Interpolation_Points.length; k++){ //loop through all the interpolation points, and render anchors
        var marker:Ball = new Ball();
        marker.x = Interpolation_Points[k].x;
        marker.y = Interpolation_Points[k].y;
        marker.scaleX = 0.5;
        marker.scaleY = 0.5;
        marker.id = k;
        marker.addEventListener(MouseEvent.MOUSE_DOWN,start_dragging);
        marker.addEventListener(MouseEvent.MOUSE_UP,stop_dragging);
        addChild(marker);
    }
}

Pretty simple actionscript? We iterate over the Interpolation_Points array, create a new Ball for each, set it’s position, add visibility by plopping it on the stage, and then attach the drag and drop functions.

Next chunk of actionscript code, Drag and Drop Functionality in Flash:

function start_dragging(event:MouseEvent):void{
    event.target.addEventListener(MouseEvent.MOUSE_MOVE, update_dragging);
    event.target.startDrag();
}
function stop_dragging(event:MouseEvent):void{
    event.target.removeEventListener(MouseEvent.MOUSE_MOVE, update_dragging);
    event.target.stopDrag();
}

function update_dragging(event:MouseEvent):void{
    Interpolation_Points[event.target.id].x = event.target.x;
    Interpolation_Points[event.target.id].y = event.target.y;
    lineDrawing.graphics.clear();
    lineDrawing = new MovieClip();
    Spline_Points = new Array();
    init_track();
}

Once we click down on a marker, add continuous updating so our spline curve in the flash tutorial will update real-time. When our mouse button is raised ( no longer holding down ), remove the continuous updating and remove the drag functionality.

Inside update_dragging, we modify the Interpolation_Points position to match the ball’s, clear the splines onscreen, reset the array, and draw again using the init_track actionscript function, which is up next.

Spline Curve Rendering:

function init_track():void{
   
    for(var k:Number = 0; k < Interpolation_Points.length; k++){ //loop through all the interpolation points, and build splines in between
       
        var point0:Point = Interpolation_Points[k];
        var point1:Point = Interpolation_Points[(k+1) % Interpolation_Points.length];
        var point2:Point = Interpolation_Points[(k+2) % Interpolation_Points.length];
        var point3:Point = Interpolation_Points[(k+3) % Interpolation_Points.length];

        for(var g:Number = 0.0; g < 1.0; g += 0.005){ //for each segment, calculate 200 spine points and store onto vector
           
            var setX:Array = calculate_catmull(g, point0.x, point1.x, point2.x, point3.x);
            var setY:Array = calculate_catmull(g, point0.y, point1.y, point2.y, point3.y);

            // .x/.y/.z labelled incorrectly
            var spline_spot:Point = new Point(setX[0],setY[0]);
            var spline_spot_first:Point = new Point(setX[1],setY[1]);
            var spline_spot_second:Point = new Point(setX[2],setY[2]);
            //end incorrect labelling


            Spline_Points.push(spline_spot);
        }
    }
   
    lineDrawing = new MovieClip();
    this.addChild(lineDrawing);
   
    lineDrawing.graphics.lineStyle(1,0xFFFF00);
    lineDrawing.graphics.moveTo(Spline_Points[0].x,Spline_Points[0].y); ///This is where we start drawing
    for(var iter:Number = 1; iter < Spline_Points.length; iter++){
        lineDrawing.graphics.lineTo(Spline_Points[iter].x, Spline_Points[iter].y);
    }
   
    var filtersArray:Array = new Array();
    var color_array:Array = new Array(0xFF0000, 0x00FF00, 0x0000FF);
    for(var j:int = 0; j < color_array.length; j++){
        var dropShadow:DropShadowFilter = new DropShadowFilter();
        dropShadow.color = color_array[j];
        dropShadow.blurX = 1;
        dropShadow.blurY = 1;
        dropShadow.angle = 0;
        dropShadow.alpha = 1;
        dropShadow.distance = 4;
        filtersArray.push(dropShadow);
    }
    setChildIndex(lineDrawing,0);
   
    lineDrawing.filters = filtersArray;
}

Here’s where the rest of the magic happens in this flash and actionscript tutorial. Loop through all of the interpolation points, grabbing every combination of 4 points in series. For each set of four control points, iterate over t from 0 to 1, for 200 separate sub-sections ( as we explained above with the mathematical equation! ). After calculating the catmull, we then push the new point onto our iteration array, to be drawn after ( spline_spot_first and spline_spot_second aren’t actually used in this tutorial, but they’re the first and second derivatives we would need if we were worried about orientation! ). Once we have an array of all the sub segments of the curve we wanted, it is time to actually draw them!

Dynamically create a new line drawing, and iteratively call moveTo for the line to update, position by position, where our curve is moving to. At the end of that, we add a series of drop shadows to give a 3D effect on the line, which actually looks pretty cool! I’ll explain in detail how dynamic filters work at a later time! We also call setChildIndex(lineDrawing, 0) to push the spline curves down to the bottom, below the markers, so they’re still easy to grab and see by the user.

Only thing after all this code, is actually calling the functions themselves!

draw_anchors();
init_track();

At that, we are done with the flash tutorial and actionscript 3 development! Press Ctrl+Enter to fire it up and see your masterpiece! I plan on adding easing, animation, and eventually 3D maneuverability to catmull rom’s so please stay tuned and be on the lookout for more, great flash cove tutorials here on the site!

-Dave at the Flash Cove (http://flashcove.net)

]]>
http://flashcove.net/795/cubic-spline-generation-in-as3-catmull-rom-curves/feed/ 2
Part 2: 3D Perspective Shooter in Flash – Paint Splatter Effect http://flashcove.net/732/part-2-3d-perspective-shooter-in-flash-paint-splatter-effect/ http://flashcove.net/732/part-2-3d-perspective-shooter-in-flash-paint-splatter-effect/#comments Sat, 21 May 2011 18:57:07 +0000 Dave http://flashcove.net/?p=732 Part 2: 3D Perspective Shooter in Flash – Paint Splatter Effect

 This is PART 2 of the flash shooter tutorial, where we learned the basics of creating a 3D perspective cannon in flash, paint splattering effects, projectile paths in AS3, sound...

]]>
Part 2: 3D Perspective Shooter in Flash – Paint Splatter Effect

 This is PART 2 of the flash shooter tutorial, where we learned the basics of creating a 3D perspective cannon in flash, paint splattering effects, projectile paths in AS3, sound effect imports, and mouse-controlled user input.

Again, all actionscript / AS3 source code and artistic effects are free to download, so go ahead and use these code segments and flash game styles in your own project.

What’s left to cover is:

  • the coloring of our cannonballs
  • colored splatter animations (both the random colors and actual masking)
  • sound effects for a realistic feel

Before we begin, as in the previous part of the tutorial, here is the source code and example flash demo of what we are trying to achieve:

Place both the actionscript and flash files in the same directory/folder, IN ADDITION TO THE CAURINA TWEENER PACKAGE, and then run the “cannon_final.fla”

To get the caurina package, either search it on google, or get the reference from my caurina tutorial, over at the flash cove link:

http://flashcove.net/163/programatic-tweening-flash/

Here’s the final flash paint cannon game, for your enjoyment:

Point and click anywhere on the screen to fire the cannon! A randomly colored ball will fly out and splatter on the backboard, in that random color, size, and orientation. This flash game DOES INCLUDE SOUND EFFECTS, so if you'd like to hear those effects when you click and when the paint hits the wall, turn up the volume!

So, let’s wrap this baby up. Next step in creation for this flash game tutorial, coloring of the cannonballs.

 

Head inside the “cannonball” MovieClip by double clicking it inside the Library. Select the middle, white filling, copy (Crtl+C), and paste in place (Crtl+Shift+V).  Right click on that new instance of the filling, and select “Convert to Symbol…“  Name it “front,” and name that single instance inside the cannonball “front” as well.

Only other thing left to do for that, is inside the “front” MovieClip, set the alpha on each gradient color to 50%.  We want the color tinting in flash to only be partial, so you can see the distinguished curves and shadows on the cannonball, not just a solid boring color.

______________________________________

Now, for the paint effect, we use a masking technique.  I covered what this is in another masking tutorial on the flashcove site, so get acquainted with it there if you haven’t heard of the concept.

The hierarchy for our flash paint splatter effect is a triple MovieClip.  We’ve got a  “splat“, which, on each frame, has a unique paint splatter picture / art. Color doesn’t matter, just a unique image on each, centered around the crosshair. I’ve got 6 in my flash source file, and all I did to find them was search “paint splatter” images online.

Wrapped around this “splat” MovieClip is a MovieClip appropriately named “splat_wrap“, all this is, is an instance of a paint splat centered on stage and tinted to a pure, 100% white color. Reason being, we need it white so that when the further outer layer is tinted, we’re layering on top an impressionable color, and not black or orange like the naturally colored paint splatter effects are on the “splat” MovieClip. I uncreatively named my instance “spla“, which will be referenced in some actionscript 3 code later on. The setup will look something like this:

The last wrapper layer is a MovieClip called “splat_anim“.  Inside, it has an instance of a “splat_wrap” and an instance of a “masking” MovieClip.  The masking layer is what we use to give the appearance of paint flying out, as compared to the paint splatter effect image immediately appearing, and looking lame.

Only tricky thing about setting this up is we need two layers. Top layer is the “masking,” with the layer checked as “Mask“, and the bottom layer sub indented, with a “splat_wrap” instance named “splatter” laying behind.  It will look like this. The yellow blob is our masking.

Last part, the creation of our “masking” MovieClip class!  Remember that what’s colored is what’s visible. All I have is three frames, first that small blob, second a larger blob, and third a massive rectangle to make sure everything below is not-masked.  On that third frame, I also put a command on the line to keep our masking from going anywhere.

stop();

And that’s all there is to the art!  Make sure though, that the outermost layer, “splat_anim“, is checked as “Export for Actionscript,” keep the name the same. We’re going to be dynamically creating instances of this for each cannonball.

____________________________________

No actionscript 3 (AS3)  code change is needed in the “cannon.fla,” only the cannonball actionscript class file. Inside the cannonball constructor class ( the cannonball() part ), we need to modify the color before being launched!  So, our new constructor will look something like this:

public function update(e:Event){

    if(time_to_live > 0){ //we're in action
        this.x += spread;
        this.y += accel;
        this.scaleX -= 0.02;
        this.scaleY -= 0.02;
       
        time_to_live--;
        accel += GRAVITY;
    }
    else{
        //remove from screen
        var splat:splat_wrap = new splat_wrap();
        splat.x = this.x;
        splat.y = this.y;
        splat.splatter.spla.id = Math.ceil(Math.random() * 6);
        splat.splatter.rotation = (Math.random() * 360);
        splat.scaleX = (Math.random()*0.50) + 0.25;
        splat.scaleY = splat.scaleX;
       
        var myColor:ColorTransform = splat.transform.colorTransform;
        myColor.color = the_color;
        myColor.alphaOffset = 0.8;
        splat.transform.colorTransform = myColor;
       
        MovieClip(root).addChild(splat);
        MovieClip(root).swapChildren(splat,this);
        this.removeEventListener(Event.ENTER_FRAME, update);
        MovieClip(root).removeChild(this);
       
    }
}

Only thing the change in the source code is in our else bracket. We’re still removing the cannonball, but we’re also creating a splatter effect! Assign it to the same position as the cannonball, pick a random drawing of the paint splatter (one of the 6 for me), randomize the size and rotation, update the color reflection, add it to the stage, and swapDepths to the front!

The only real tricky thing in this code is assigning one of the 6 paint splatter effect drawings. In Flash, some things work on the back-end that we don’t understand. Since the Masking is changing frames 3 times, a new instance of splat is also being re-rendered, typically resetting the paint splatter drawing back to frame one. To avoid that, we set the “.id” to the frame we want, and then make a modification inside the “splat” MovieClip.

Inside the frame 1 source code, add the following lines:

this.gotoAndStop(this.id);
stop();

This should make the paint splatter effect decision seamless every time.

_________________________________

If you were to compile and run this flash tutorial right now, everything should work flawlessly, except where’s the sound effects!?

They’re actually trivially easy to implement. First thing though, is you need to find some free sound effects. Either you can look online, or just use the ones I did,



 

You can import these sound effects in to flash by selecting File in the top left -> Import -> Import to Library.. . Find the two mp3 files, and Ctrl+Click them onto the list.

Inside the library, find both instances, check the “Export for Actionscript” under properties, and name them “cannonmp3” and “thudmp3” respectively for Actionscript use.
________________________

Inside the cannonball.as file, right up with all the as3 variable declarations, add the follow line to import sound effects in flash.

var thud:thudmp3= new thudmp3();

And down inside the update function, in the else bracket, add one more line:

thud.play();

We now have the landing / paint splatter sound effect in our flash game tutorial!

Those same two lines also need to be placed inside the cannon.fla, except we need cannonmp3, not thudmp3. See if you can do that one yourself, and if you’re really stuck, just reference the absolutely free AS3 source code available for download at the top of the page!

Compile and run this flash tutorial game demo via “Ctrl+Enter” and you’ll see the beautiful flash masterpiece you just created!
_______

Thanks for tuning in to another amazingly in-depth and free flash tutorial on paint splatter effects, 3D perspective, and importing sound effects!

-Dave at the FlashCove (http://flashcove.net)

]]>
http://flashcove.net/732/part-2-3d-perspective-shooter-in-flash-paint-splatter-effect/feed/ 3
Countdown Timer Animation (Dynamic) in Flash AS3 http://flashcove.net/693/countdown-timer-animation-dynamic-in-flash-as3/ http://flashcove.net/693/countdown-timer-animation-dynamic-in-flash-as3/#comments Tue, 10 May 2011 02:18:07 +0000 Dave http://flashcove.net/?p=693 Countdown Timer Animation (Dynamic) in Flash AS3

  I play a lot of Call of Duty: Black Ops, and every time an online multiplayer game starts up, there are flashing yellow numbers for the countdown before the...

]]>
Countdown Timer Animation (Dynamic) in Flash AS3

 

I play a lot of Call of Duty: Black Ops, and every time an online multiplayer game starts up, there are flashing yellow numbers for the countdown before the game begins. While they look okay, I figure I could make something look a little cooler in an easy flash tutorial to submit to the flash cove. This flash tutorials encompasses knowledge about embedding fonts, zoom effects, and timer functionality within flash and as3. Also, rather than storing each number individually in a seperate image, we dynamically use a countdown, updating a Dynamic text field instead for better efficiency. I hope that after reading through this free flash countdown tutorial, and observing the actionscript source code, you too can create a great countdown timer in flash for your very own flash game or flash application.

The actionscript source code and full source FLA file are available right here, along with an interactive flash demo of what you can achieve after covering this easy countdown timer flash tutorial.

Place the actionscript / flash file “countdown_demo.fla” in a directory/folder on your PC, and then run it using (Ctrl + Enter)

 

Here’s the mouse animation in flash we are looking to achieve:

Press the start button to see our Call of Duty Black Ops flash countdown in action! Once it is done, you can also replay via the button bottom-left in the flash demo.

So, let’s get started on the development.

Open up a new flash document. Standard 550 pixels by 400 pixels. Insert a new MovieClip, and call it “countdown“. Inside the MovieClip, create two Dynamic text boxes, and make sure they align top-left to the center! This is EXTREMELY IMPORTANT for this tutorial, or else the countdown timer’s flash font will not zoom properly! As far as font goes, I used joystix, a really great set available at the link. In this next step I’ll teach you how to embed this specific font, or any other font at that too in flash.

Up on the very top right of your Library in Flash, click the small button, and then select “New Font…

Once inside, set the name to be “joystix64” set the actual font to Joystix, and make sure the size is set to 64, which is the size we will be using in this flash tutorial!

For the two sets of text inside our countdown, set both to a “Dynamic Text Box,” and make sure the font you are using for them is NOT Joystix, but actually joystix64, which should be somewhere at the top of the font selection list.  Additionally, we need to set the embedded characters for each of the text instances. In the property manager, there’s a button titled “Character Embedding..” click that, and then embed the following characters: Numerals (0-9) and the individual letters “GO!”  As seen in the picture; make sure the total is 14 characters like mine!

Once this is all complete, make sure you actually give both countdown text instances a label! I made mine “text1” and “text2“  Once you’ve done that, the drawing up of our fonts in this flash tutorial is complete, all that’s left is some actionscript 3 coding.

 

Without further adieu, here is the actionsciprt 3 code for this easy countdown timer (Call of Duty style!) flash tutorial:

var beginning:Number = getTimer();
stage.addEventListener(Event.ENTER_FRAME,countdown_function);

function countdown_function(e:Event):void{
    var current:Number = getTimer() - beginning;
    if(current > 11000){
        countdown.text1.text = "GO!";
        countdown.text2.text = "GO!";
        stage.removeEventListener(Event.ENTER_FRAME,countdown_function);
        return;
    }
    else if(current > 10000){
        countdown.text1.text = "GO!";
        countdown.text2.text = "GO!";
    }
    else{
        countdown.text1.text = 10 - Math.floor(current / 1000);
        countdown.text2.text = 10 - Math.floor(current / 1000);
    }
    countdown.scaleX = 1 + 100 / ((current % 1000) + 1);
    countdown.scaleY = countdown.scaleX;

}

The beginning timer value just grabs the local value for a start time to reference against. getTimer() gives us the number of milliseconds passed so far in the flash game. So, we add an ENTER_FRAME listener, grab the difference between present time and starting time (in milliseconds), and do a check..

If time time is less than 10 seconds (10,000 milliseconds), set the text values for both our instances to the right number of seconds.. AKA

10 - Math.floor(current / 1000);

Also, set the scale (size) of our text to be the inverse of the inter-second moment. The closer we are to zero of mod 1000, the larger we are (scale of 2), the closer we are to 999 of mod 1000, the smaller we get (scale of 1). This gives us a zoom-in effect for the countdown timer in the flash tutorial.

If time time is greater than 10 seconds (10,000 milliseconds), but less than 11 seconds (11,000 milliseconds), set the font to “GO!” rather than a number, as we’ve hit zero.

If time is greater than 11 seconds (the first if statement in the actionscript 3 code), remove the frame listener, and leave the text statically as “GO!”

That’s all there is to it for the flash as3 code! Just be sure, that beforeyou run the flash game, you actually have an instance of the countdown text on the stage, labeled as “countdown” so the actionscript 3 code has something specific to reference!

I appreciate you guys tuning in to this sweet Call of Duty: Black Ops style countdown timer flash tutorial! As always the as3 source code is free to duplicate, so get developing!

-Dave at the Flash Cove (http://flashcove.net)

]]>
http://flashcove.net/693/countdown-timer-animation-dynamic-in-flash-as3/feed/ 12
Animated Mouse Effects in Flash http://flashcove.net/666/animated-mouse-effects-in-flash/ http://flashcove.net/666/animated-mouse-effects-in-flash/#comments Mon, 09 May 2011 02:13:13 +0000 Dave http://flashcove.net/?p=666 Animated Mouse Effects in Flash

  Mouse animations and trailing effects are perfect for flash based websites, online advertisements, and flash video games. Not only that, but mouse animations in flash are extremely easy to...

]]>
Animated Mouse Effects in Flash

 

Mouse animations and trailing effects are perfect for flash based websites, online advertisements, and flash video games. Not only that, but mouse animations in flash are extremely easy to customize and edit to your liking, so they can be perfect for your specific web application or flash game. What we are going to create in this easy flash tutorial is a trailing glow effect that will follow your mouse around, and pulsate when idle.

The actionscript source code and full source FLA file are available right here, along with an interactive flash demo of what you can achieve after covering this easy mouse animation flash tutorial.

Place the actionscript / flash file “mouse_trail.fla” in a directory/folder on your PC, and then run it using (Ctrl + Enter)

 

Here’s the mouse animation in flash we are looking to achieve:

Mouse the mouse around quickly, and watch the glow follow in our flash game demo. If you keep your cursor still, the glow will pulsate around the skull for a nice flash effect.
  1. First step, open a new Flash Document, Actionscript 3, standard size of 550 pixels by 400 pixels.
  2. Import some kool cursor art for your mouse. I used a skull, which you can grab right here, below. Place it inside a new MovieClip (Ctrl + F8), and then drag a single instance of the new MovieClip on to the main flash stage, and label that specific instance of the MovieClip as “skull
  3. Make another new MovieClip (Ctrl + F8), and label it “trail“. Inside, all you need to draw is a 100 pixel by 100 pixel perfect circle, black, centered around the cross index in the MouseClip drawing plane.  After drawing, exit out to the main Scene 1 frame, right click the “trail” in the library, select Properites, and then check the “Export for Actionscript” box.
  4. Third and final thing to draw in this easy flash tutorial is some gridwork on the main stage. Select the brush tool, a light gray color, and hold down the SHIFT button while clicking and dragging to create some straight lines horizontally and vertically across the stage. They don’t need to be in any type of MovieClip, on-stage is just fine.
  5. Once all the flash art is drawn (the circle, skull, and criss-cross lines), it’s time to write the small amount of actionscript 3 code neded to get this easy flash tutorial running, and for the mouse animation effects to get glowing. Right click the first frame on the main stage, and select Actions down on the bottom. Enter the following as3 code in to the flash code box..
var blur_filter:BlurFilter = new BlurFilter(40,40,1);
init()
stop();

function init():void{
    skull.startDrag(true);
    Mouse.hide();
    stage.addEventListener(Event.ENTER_FRAME,mm);
    function mm(e:Event):void{
        if(Math.random() < 0.30){
            createTrailBall();
        }
    }
}
 
function createTrailBall ():void {
 
    //Create a new circle instance
    var trailBall:trail=new trail();
   
    trailBall.cacheAsBitmap = true;
    //Position the trailing circle in the same position where the mouse is
    trailBall.x = mouseX;
    trailBall.y = mouseY;
    //add the blur to smooth the edges
    trailBall.filters = new Array(blur_filter);
 
    //Add ENTER_FRAME to animate the trailing circle
    trailBall.addEventListener (Event.ENTER_FRAME,animateTrailBall);
 
    //add it to the bottom of the stage, so it appears below the grid onscreen.
    addChildAt (trailBall,0);
}
 
function animateTrailBall (e:Event):void {
    //In each frame, reduce the alpha and the scale of the trail ball.
    e.target.alpha -= 0.10;
    e.target.scaleY += 0.10;
    e.target.scaleX += 0.10;

    var myColor:ColorTransform = e.target.transform.colorTransform;
    myColor.color= 0xFFFFFF * (1 - e.target.alpha);
     
    e.target.transform.colorTransform = myColor;

   
    //if alpha is less than 0; remove the ball from the stage
    if (e.target.alpha < 0) {
        e.target.removeEventListener (Event.ENTER_FRAME,animateTrailBall);
        removeChild ((MovieClip)(e.target));
    }
}

We have an initialization function which adds the ENTER_FRAME listener. Inside that listener, every frame, we generate a random number to check if we should create a glowy ball in flash. If we do need to, we call createTrailBall(), which sets up the x and y positions, caches it for optimization, adds the blur filter (from the initialization at the top), starts the update function, and draws to the screen. In the update function, animateTrailBall(), we blow up in size, fade away, and drift to a white color. Once alpha is zero (we are completely invisible), we promptly remove and delete this instance of the glowy ball.

And that’s all there is to it! With that, this easy flash tutorial is complete. Compile and run the flash tutorial and you should get something very similar to the flash demo at the top of the page.

Thanks for tuning in to another great, free, and easy flash game tutorial!

- Dave at the Flash Cove (http://flashcove.net)

]]>
http://flashcove.net/666/animated-mouse-effects-in-flash/feed/ 1
3D Perspective Shooter in Flash – Paint Splatter Effect http://flashcove.net/621/3d-shooter-flash-paint-splatter/ http://flashcove.net/621/3d-shooter-flash-paint-splatter/#comments Sat, 07 May 2011 18:00:01 +0000 Dave http://flashcove.net/?p=621 3D Perspective Shooter in Flash – Paint Splatter Effect

  This large and detailed tutorial will teach you the basics of creating a 3D perspective cannon in flash, paint splattering effects, projectile paths in AS3, sound effect imports, and...

]]>
3D Perspective Shooter in Flash – Paint Splatter Effect

 

This large and detailed tutorial will teach you the basics of creating a 3D perspective cannon in flash, paint splattering effects, projectile paths in AS3, sound effect imports, and mouse-controlled user input. All actionscript / AS3 source code and artistic effects are free to download, and I hope using these examples you too can create some pretty awesome flash games, applications, and effects. There are a couple subtle flash effects in here; you may wish to follow along using my “cannon.fla” and “cannonball.as” source code I attached below. Playing with the demo at the top of this flash tutorial page will show you how effective such a simple paint effect can be in Flash.. and, at that, I am proud to present the following…

The final 3D paint cannon source code can be found right here:

Place both the actionscript and flash files in the same directory/folder, IN ADDITION TO THE CAURINA TWEENER PACKAGE, and then run the “cannon.fla”

 

To get the caurina package, either search it on google, or get the reference from my caurina tutorial, over at the flash cove link:

http://flashcove.net/163/programatic-tweening-flash/

Here’s the final flash paint cannon game, for your enjoyment:

Point and click anywhere on the screen to fire the cannon! A randomly colored ball will fly out and splatter on the backboard, in that random color, size, and orientation. This flash game DOES INCLUDE SOUND EFFECTS, so if you'd like to hear those effects when you click and when the paint hits the wall, turn up the volume!

So, let’s start the development..

First thing we need to draw is a cannon (in 3D perspective.) Open up a new MovieClip, and name it “cannon.” Inside, draw your art such that the very bottom center base of your cannon art is based at the center index point for the MovieClip.  The indexing should look something like the setup in the picture below; hopefully you can draw a letter better looking cannon too lol.

Next step, insert a new layer inside the “cannon” MovieClip,  and draw a small little red dot. Right Click that red dot, and say “Convert to MovieClip,” call it “launchspot“.  Click back in to the “cannon” MoveiClip, select the instance of the “launchspot,” and name this one specifically “launchspot” again. When we access from as3, this is the name we are going to call.  The reason though, for this little dot existing, is that when I click to fire cannonballs, I need an exact place to launch to cannonballs from, so it looks realistic.  If this  is located on the cannon at all times, I can use it’s internal position to index and place my procedurally generated MovieClips from the actionscript / AS3 code.  You should place the instance of the “launchspot” MovieClip somewhere at the base of the barrel of the cannon, just like in this picture from the flash game tutorial:

Once the launchspot is set for the cannon MovieClip in the flash ame, it is time to setup the CANNONBALL. Insert a new MovieClip via Insert -> New Symbol.., and name it “cannonball“.  Inside, using the sphere tool from inside the flash IDE, draw a radial colored circle with a thick (5 pixel or so) black border.  Based the alignment of the game’s cannonball around the center.  My flash cannonball looks like this:

Once the art is done, we actually need to export the “cannonball” for use in Actionscript 3 as well. Find the cannonball in the flash library, Right Click -> Properties -> Check the “Export for Actionscript,” and leave the name as “cannonball“  We’re done with this art stuff for now, lets get the the as3 source code!

Go the the main “Scene 1″ part of yuor flash porgram, and on frame 1 of the file, under the “Actions” tab, write in the following as3 code..

import caurina.transitions.Tweener;  //import the Tweener class from the Caurina package.

stage.addEventListener(MouseEvent.MOUSE_MOVE, mm);
stage.addEventListener(MouseEvent.MOUSE_UP, mu);

function mm(e:MouseEvent):void{
cannon.x = 275 - (275 - mouseX)*0.05;
cannon.rotation = -(275 - mouseX)*0.05;
}

function mu(e:MouseEvent):void{
var anglec:Number = -cannon.rotation;
var xposc:Number = cannon.x;
Tweener.addTween(cannon, {y: 540, x: xposc + anglec*(0.5),  time: 0.035, transition: "linear"});
Tweener.addTween(cannon, {y: 530, x: xposc, time: 0.055, delay: 0.035, transition: "linear"});

//make cannonball
var loca:Point = new Point(cannon.launchspot.x,cannon.launchspot.y);
var glob:Point = cannon.launchspot.localToGlobal(loca);
glob.x = 275 + (glob.x - 275)*0.4 - anglec;
var cb:cannonball = new cannonball(glob.x, 340, -anglec*0.25 - (anglec*0.1), 400 - mouseY);

addChild(cb);
swapChildren(cb,cannon);
}

We only need two global listeners on the flash game demo, a MOUSE_MOVE and a MOUSE_UP (mouse_up is the same as a mouse click, but only fires when we lift the key.)  In the MOUSE_MOVE function, “mm” all we do is move the cannon left and right, and also give it a little tilt with the .rotation to help make the 3D perspective look a little more realistic in our flash game.  The 275 value just represents where our instance of the cannon sits on the stage, dead center on a 550 pixel width scene..

In the MOUSE_UP function, we are doing two things.. a kickback, or jiggle, on the cannon when it’s fired so it looks realistically 3D in flash, and of course, the actual generating of a cannon ball.  The  two Tweener calls, using the caurina add-in package, give us our kickback animation. To learn how to do this, you can visit the Caurina tweening tutorial to get a better understanding at this link, http://flashcove.net/163/programatic-tweening-flash/.  The second part, where we make the cannon ball, we have to know the point of launch first, since it is not simply our Mouse Position. To do this, we use the “launchspot” MovieClip from inside the cannon! The only thing though, is it’s position is RELATIVE to the center of the inside of the MovieClip, not to the global stage coordinates of our flash game.

Thankfully though, there’s a function called localToGlobal(), that can do a conversion for us to the stage coordinates in the flash game tutorial! All we have to do is pass in the local coordinate points (I.E. the cannon.launchspot.x and cannon.launchspot.y in loca) to localToGlobal, and call it with the cannon prefix.

This positioning isn’t perfect though with the localToGlobal() position, so after a few little test tweaks, we get much more realistic projection points in flash after modifying glob.x and messing with the y input value for the cannon ball constructor. Speaking of the constructor, it takes in three variables, the x-position, y-position, and velocity.  The code on the backend for this cannon ball is in the actionsciprt 3 / AS3 file cannonball.as. We will cover this code in just a second.

The final part, addChild() and swapChildren() flash functions, simply add the cannonball to the screen and then swaps depths with the cannon launcher itself in flash. Reason we want to do this, is because we want the cannon ball to come from BEHIND the cannon, and addChild() automatically adds to the top. swapChildren() easily fixes that problem and makes the cannon ball launch correctly from behind when the flash game tutorial is compiled and run.

____________________________________________________

The main function code is now complete, time for the separate actionscript 3 / AS3 file, cannonball.as:

package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.filters.*;
import flash.geom.ColorTransform;

public class cannonball extends MovieClip
{
    public static const START_DELAY:Number = 10; //how long our fountain will spurt color
    public static const VELOCITY:Number = 10; //how fast our particles shoot up
    public static const GRAVITY:Number = 0.75; //how quickly are the particles pulled down

    public var start_delay:Number;
    public var time_to_live:Number;
    public var color:uint;
    public var spread:Number;
    public var accel:Number;

    public function cannonball(xpos:Number, ypos:Number, spread_in:Number, veloc:Number)
    {
        this.x = xpos;
        this.y = ypos;

        time_to_live = 50;
        var ratio:Number = (veloc / 400);
        veloc = (70*ratio) + 180;
        accel = -veloc/10;
        spread = spread_in;

        this.addEventListener(Event.ENTER_FRAME, update);
    }

    public function update(e:Event){

        if(time_to_live > 0){ //we're in action
            this.x += spread;
            this.y += accel;
            this.scaleX -= 0.02;
            this.scaleY -= 0.02;

            time_to_live--;
            accel += GRAVITY;
        }
        else{
        //remove from screen
        this.removeEventListener(Event.ENTER_FRAME, update);
        MovieClip(root).removeChild(this);
        }

    }

}
}

This  actionscript 3 source code looks surprisingly like the particle effect setup I covered in a previous tutorial, which can be found right here: http://flashcove.net/353/particle-effects…structure/.  In fact, the only real difference in the update portion is that I’m shrinking the scale (AKA size) of the cannonball so it looks like it is shrinking off in to the distance.

For the initialization in the cannonball() constructor function though, we set the X and Y positions to what was given to us in the passed-in parameters.  What is passed in from the veloc parameter is a number representing where the mouse was at on the Y-axis at the time of calling. Since the height of the screen is 400 pixels, I grab a percentage ratio of how far along the mouse position is, multiply that percentage  by the maximum velocity I want (70), and add it to a base value (180o ensure my balls never get shot below the screen height. I decided on these two values, 70 and 180, by using the actionscript trace command and some trial and error on velocity values.

Assuming you have everything setup correctly, and both the cannonball.as code and the main scene code written properly, if you compile and run the flash game via Ctrl + Enter, you will get the current state of the 3D perspective cannonball game..

Point and click anywhere on the screen to fire the cannon!

PART 2 of this flash game tutorial will be put up online soon, so please stay tuned! In the next part we will cover the sound effects, colorization, and paint splatter effects that you saw in the flash game demo at the top of the page!

Thanks for tuning in to another great, free, flash game tutorial!

- Dave at the Flash Cove (http://flashcove.net)

]]>
http://flashcove.net/621/3d-shooter-flash-paint-splatter/feed/ 2
Part 2: Laser Beams and Smoke Effects in Flash Games http://flashcove.net/577/part-2-laser-beams-and-smoke-effects-in-flash-games/ http://flashcove.net/577/part-2-laser-beams-and-smoke-effects-in-flash-games/#comments Tue, 03 May 2011 03:00:16 +0000 Dave http://flashcove.net/?p=577 Part 2: Laser Beams and Smoke Effects in Flash Games

Continuing from PART 1 of “Laser Beams and Smoke Effects in Flash Games,” we now need to integrate the smoke effects and easter egg collision detection in to our flash...

]]>
Part 2: Laser Beams and Smoke Effects in Flash Games

Continuing from PART 1 of “Laser Beams and Smoke Effects in Flash Games,” we now need to integrate the smoke effects and easter egg collision detection in to our flash game!

The final laser and smoke source code can be found right here:

Open up the “lasers_and_smoke.fla”, and then run it by pressing Ctrl + Enter in Flash.

And, as a reminder, here’s what were going for with this laser and smoke flash game:

Click down on the mouse to charge your lasers. If you hold the laser beam over any of the Easter eggs or the counter top, you will see the smoke start to bellow out!

Once we are caught up with PART 1 of the flash game tutorial,it is time to implement the smoke effect!  To begin, let’s draw the art.

On the top menu, select Insert -> New Symbol (Ctrl + F8), set it to be a type MovieClip and name it “smoke“. Inside, draw a small circle (50px by 50px), centered around the origin. For the color, make it a two-tone gradient, with a light gray in the center, fading to a darker gray on the outside. The outside, darker gray; give it a low alpha (10%-ish) to help keep focus on the center color. Settings should look somewhat like the picture below in flash.

Once the smoky circle is drawn, we’re going to insert yet another MovieClip. On the top menu, select Insert -> New Symbol (Ctrl + F8), set it to be a type MovieClip and name it “smoke_shell“.  Once inside this blank MovieClip shell, drag and drop an instance of the  “smoke” MovieClip from the library in to the “smoke_shell,” and center it about the axis point.

Next, select that instance of the smoke on the stage, and add a Blur Filter using the “Filters” submenu (mine’s on the left-hand side for the Designer Flash CS4 Layout). Set the blur intensity to be 28 for both BlurX and BlurY. You should get something sleek looking like this smoke particle:

 

Once that’s done, we need to export the “smoke_shell” for actionscript.  Find the MovieClip in the flash’s library tab, Right Click -> Properties, and then check the “Export for Actionscript” box. Then we should be good to go; time to draw some easter eggs, and then write some actionscript 3 code (AS3).

________________________________________________________________________________

For the easter eggs in the flash game, we have just a single MovieClip, and several frame inside all with different art. Once a brand new instance of the egg is created, it randomly will chose on of the art sets to display. This is a great way to introduce random objects and detail in to your flash games and applications without too much additional effort needed. Just a couple different sets of art, and you are good to go!

With that, on the top menu, select Insert -> New Symbol (Ctrl + F8), set it to be a type MovieClip and name it “egg“.  Inside I just drew a nice, oblong, egg looking oval, and copied and pasted it across 10 frames. For each frame, draw a little bit of art on each one, each unique, and different colors!

Then, on the first frame, Right Click -> Actions, and insert this line of code:

 this.gotoAndStop(Math.ceil(Math.random() * 10));

What that does is guarantees the egg picks, randomly, one of the 10 drawn art sets, and moves it into position upon creation of the instance on our flash stage.

My egg setup looks something like this, which you can grab in the lasers_and_smoke.fla file above if you don’t want to draw something yourself.  (I’ve also got the shade and shadow layers to give a dark overtone on the egg, make it fit the flash tutorial scene a little nicer.)

Once we’re set on the art, head back to the main “Scene1″ stage. Drag and drop several instances of the egg (from the flash library) on to the stage, in a nice assortment, just like you see in the demo at the top of the page.  Give each instance of the egg a unique name, as follows:  “egg1,” “egg2,” “egg3,” “egg4,” etc..  Reason for this, inside our actionscript 3 source code, the laser is going to iterate over potential collisions (eggs) to determine if we should draw a flash smoke effect or not.

(I also made a MovieClip containing the ‘countertop’ that the eggs are resting on. Feel free to draw one, and drag a single instance on to the stage and label it ‘counter’ as I did, so it can be accessible by our actionscript 3 code references.)

 

After the smoke particles, eggs, and counter tops are drawn in flash, all that’s left is a little actionscript 3 (AS3) code!

____________________________________________________________

The only thing that needs to be updated in our preexisting actionscript 3 (AS3) code is the enter_frame function. In the else bracket, we are going to add a couple lines of as3 code, as follows:

FROM THIS:

else{
    percent_level = 1; //if we do, keep it at a 1:1 ratio so it doesn't over shoot
}

TO THIS:

else{
    if(Math.random() < 0.25){
        for(var iter:Number = 1; iter < 19; iter++){
            if(MovieClip(root)["e"+iter].hitTestPoint(mouseX,mouseY,true)){
                make_smoke();
                break;
            }
        }
        if(counter.hitTestPoint(mouseX,mouseY)){
            make_smoke();
        }
    }
    percent_level = 1; //if we do, keep it at a 1:1 ratio so it doesn't over shoot
}
drawLaser(percent_level); //pass the value in

 

I have 19 eggs on my screen, and I labeled them “e1,” “e2,” “e3,” etc.. So, to check collision with my laser effect (just the mouseX/mouseY positions), I iterate over all possibilities and do a HitTestPoint() with my current mouse positions! Once a collsiion is found to be true, we then call the function make_smoke() (to be implemented in just a second).  After that collision is found, we then put the line of code break;

Once that first collision is found, we don’t need to keep looking because one egg was already found! So to save computation time, we can just exit the for loop and move on to the next task.

Also appended just below the for loop is a quick check against the countertop to see if we are colliding with that too. Nothing new or special.

_____________________________________________

All that’s needed now is our make_smoke() function, and it’s helper/destructor function dissipate(). The as3 code is as follows:

function make_smoke(){
    var smokie:smoke_shell = new smoke_shell();
    smokie.x = mouseX + ((Math.random() * 40) - 20);
    smokie.y = mouseY + ((Math.random() * 20) - 10);
    smokie.scaleX = 0.50;
    smokie.scaleY = 0.50;
    smokie.addEventListener(Event.ENTER_FRAME,dissipate);
    addChild(smokie);
}

function dissipate(e:Event):void {
    e.target.y-=2;
    e.target.alpha -= 0.01;
    e.target.scaleX += 0.0025;
    e.target.scaleY += 0.0025;

    if(e.target.alpha <= 0){
        e.target.removeEventListener(Event.ENTER_FRAME, dissipate);
        e.target.parent.removeChild(e.target);
        delete e.target.parent;
    }
}

In make_smoke(), all we do is create a new smoke movieclip instance, set it’s position to the current mouse position (in addition to a little jiggle so it looks random), shrink the scale down a bit, add the dissipate ENTER_FRAME event listener, and draw it to the screen.

Inside dissipate, we drift the smoke upwards on the screen, fade it’s alpha out, and grow it in size to give a “dissipation” effect in flash.  Once the smoke particle has completely lost visibility on the stage, remove the ENTER_FRAME event listener, remove it from view, and delete the object.

 

That’s it! Compile and run, and you should get something very similar to the demo shown above at the top of this flash game tutorial.

(TO VIEW THE FIRST PART OF THIS TUTORIAL, GO TO THE LINK DIRECTLY BELOW!)

http://flashcove.net/496/laser-and-smoke-effects/

Once again, enjoy the use of the absolutely free flash and as3 source code, and thanks for tuning in!

-Dave at the Flash Cove (http://flashcove.net)

 

]]>
http://flashcove.net/577/part-2-laser-beams-and-smoke-effects-in-flash-games/feed/ 2
Custom Cursors and Crosshairs in Flash http://flashcove.net/549/custom-cursors-and-crosshairs-in-flash/ http://flashcove.net/549/custom-cursors-and-crosshairs-in-flash/#comments Thu, 28 Apr 2011 21:48:57 +0000 Dave http://flashcove.net/?p=549 Custom Cursors and Crosshairs in Flash

Unique crosshairs, reticules, and cursors are a staple of any flash game. Having something unique to represent mouse movement other than the typical Mac and Window’s cursors really helps your...

]]>
Custom Cursors and Crosshairs in Flash

Unique crosshairs, reticules, and cursors are a staple of any flash game. Having something unique to represent mouse movement other than the typical Mac and Window’s cursors really helps your flash game or application stand out. Thankfully too, it is extremely easy to implement! I’ll show you guys two simple ways to implement a unique custom flash cursor, and you can decide which you like best!

  • First thing, open up a new flash document using Actionscript3 (AS3). I set the dimensions of mine to 300px by 200px, and the framerate up to 30.  Reason being, both the implementations for our custom flash cursor effect depend on the flash application’s framerate, so the higher a framerate, the smoother an effect you will achieve.
  • Step two, let’s create the art for our custom movieclip!  On the top menu, select Insert ->New Symbol (or press Ctrl+F8), and call it “cursor” with a MovieClip type.
  • Inside the movieclip, draw whatever custom art you like, but be sure that the small cross on the screen (you center of reference) stays wherever you want the tip of your mouse point to reference to. Personally, I drew a little sword that looks like the one below.   Black bordering, brown handle, with orange-ish plating, and a two-tone gray gradient for the blade itself. See if you can draw something too (probably much better than my sword lol). Notice how I set up the art so that the tip points at the cross inside the MovieClip for center of reference, this is crucial.
  • Once the art is complete, it is time to create an instance of our cursor! Back out of the MovieClip by pressing the tiny breadcrumb button “Scene1″ above your drawspace. Now, find our “cursor” movieclip label in the library, and then click and drag onto the stage to create an instance. In the properties manager, set our label to be “sword_cursor” as seen in the image below. We need this reference name inside the actionscript3 code.
  • It’s now time to plug in a little actionscipt3 (AS3) code on the main stage flash frame.  Right click on frame one, and select “Actions” down at the bottom. Enter the following code:
  • sword_cursor.startDrag(true);
    Mouse.hide();
  • You could also write the actionscript3 code like this is you prefer it more:
  • stage.addEventListener(MouseEvent.MOUSE_MOVE,cursor_update);
    Mouse.hide();

    function cursor_update(e:MouseEvent):void {
        sword_cursor.x = mouseX;
        sword_cursor.y = mouseY;
    }
  • One more thing before compiling, we also want a pretty glow effect. Go click on the instance of the “sword_cursor” on the stage, and then down in the FILTERS menu, press the small button on the bottom left that looks like a flipped page. The rollover comment says “Add filter.” Press that and then select  “Glow.”  I left mine in the default mode with the red glow.
  • Once that is done, compile your code via Ctrl+Enter, and Voila! You’ll get the flash application like below:

The demo of this application is here:

Pretty simple, huh? To get your own art into the cursor, just modify the “cursor” MovieClip to get something new.

Maybe something like this..

 

or even this..?

 

Either way, thanks for tuning in.

Thanks again!

-Dave at the FlashCove (http://flashcove.net)

]]>
http://flashcove.net/549/custom-cursors-and-crosshairs-in-flash/feed/ 4
Laser Beams and Smoke Effects in Flash Games http://flashcove.net/496/laser-and-smoke-effects/ http://flashcove.net/496/laser-and-smoke-effects/#comments Thu, 28 Apr 2011 01:48:54 +0000 Dave http://flashcove.net/?p=496 Laser Beams and Smoke Effects in Flash Games

OMG LAZORZ!!! This tutorial covers the development of a simple laser beam effect in Flash.. and along with that, the generation of a smoke particle effect in AS3 to add...

]]>
Laser Beams and Smoke Effects in Flash Games

OMG LAZORZ!!! This tutorial covers the development of a simple laser beam effect in Flash.. and along with that, the generation of a smoke particle effect in AS3 to add to the scene’s mood. Lasers are a fun feature to add to any video game, and using the knowledge from this flash AS3 tutorial and a little more polish, you will be able to create a truly awesome laser beam flash game.

Not only that.. but since this is so close to the holiday.. IT’S EASTER THEMED! (Kinda.)

Source code can be found right here:

Open up the “lasers_and_smoke.fla”, and then run it by pressing Ctrl + Enter in Flash.

And a demo of this application is here:

Click down on the mouse to charge your lasers. If you hold the laser beam over any of the Easter eggs or the counter top, you will see the smoke start to bellow out!

TUTORIAL STEPS:

  1. First and foremost, we need something to shoot lasers from. What I used in this tutorial was the drawing of a skull I made. You can either grab that right here, save as, and import into your flash project; or simply use the assets form the completed tutorial lasers_and_smoke.fla file I referenced above.
  2. Place the skull somewhere in the upper left-hand corner of the stage. We’re going to have to calculate the exact position of his eyes later on to anchor our flash laser effect down.
  3. Once the skull is in place, we are going to need to set up a global Boolean, and three event listeners, Event.ENTER_FRAME, MouseEvent.MOUSE_DOWN, and MouseEvent.MOUSE_UP.  When the mouse goes down, flip on the global boolean, when it goes up, flip the boolean off. This will give us a real-time response rate for the laser effect, and almost all flash game input is setup using this type of framework.  The code skeleton will look something like this!
var mouseState:Boolean; // true for down, false for up

function init():void{
    stage.addEventListener (Event.ENTER_FRAME, enter_frame);
    stage.addEventListener (MouseEvent.MOUSE_DOWN, mouse_down);
    stage.addEventListener (MouseEvent.MOUSE_UP, mouse_up);
}

function mouse_down (e:MouseEvent):void {
    mouseState = true;
}

function mouse_up (e:MouseEvent):void {
    mouseState = false;
}

function enter_frame (e:Event):void {
    if(mouseState){
        //logic for when the mouse is down

        //AKA draw lasers and do hit detect for smoke
    }
}

We’ve got the two listeners for switching mouse states, and ENTER_FRAME checking that boolean. If the boolean mouseState is true, execute laser generation sequence.

4.  When it is time to create the laser, we have got to pick one of two options.  We can either have the laser effect appear instantly, hitting our target mouse position, or have the laser “beam out” to the position over a short series of frames. Obviously, the beam out effect looks much cleaner, and since it isn’t too much more actionscript 3 code to enter, we’ll go ahead and implement the animated laser beam pullout.

With that, we need three more global variables, laserbeam1 MovieClip, laserbeam2 MovieClip, and our “percentage” Number, to show how far along our beam generation has proceeded. The actionscript 3 code looks like this (placed at the top of the file):

var laserbeam1:MovieClip;
var laserbeam2:MovieClip;
var percent_level:Number = 0;

Since we are creating these two laser beams dynamically, we also need to reserve a block of memory for them, and add to stage. Our new (and final) initialization function now looks like this:

function init():void{
    laserbeam1 = new MovieClip();
    laserbeam2 = new MovieClip();
    stage.addChild(laserbeam1);
    stage.addChild(laserbeam2);

    stage.addEventListener (Event.ENTER_FRAME, enter_frame);
    stage.addEventListener (MouseEvent.MOUSE_DOWN, mouse_down);
    stage.addEventListener (MouseEvent.MOUSE_UP, mouse_up);
}

Looking sharp! Next step.

5.  Let us go ahead and create a function called drawLaser().  With this separate function piece, we can call just this one line in our ENTER_FRAME event, and the code will cleanly execute every time. It looks nicer, and is easier to understand for our fellow readers.

First thing’s first, since our skull has TWO eye sockets, we are going to draw TWO laser beams (of course that’s why we create two instances in the init() function).  Our laser beams are completely procedural.. no tweening or pre-created movieclips. Since everything is dynamically drawn, it is easy to tweak, and easy to update at your convenience. To update a color, simply change one line; to change the width, just update one variable, etc.. I hope, after seeing many of the flash tutorials on flashcove.net, you see there are great benefits in creating things dynamically. Not only is it faster, but also more customizable.

The laser beam effect in this flash game tutorial consists of a single line drawn, in addition to a blur and glow filter. The line is a dark red, the glow is a light red, and the blur effect gives softer edges for a polished representation. This is done as follows:

function drawLaser(percent:Number):void {
    laserbeam1.graphics.clear(); //first clear the old drawings (if any)
    laserbeam1.graphics.lineStyle(4,0xF75D59); //set line settings to 4px width, and a darkish red

    laserbeam1.graphics.moveTo(60,65); ///This is where we start drawing
    laserbeam1.graphics.lineTo(60 + (mouseX-60)*percent, 65 + (mouseY-65)*percent); //this is where we draw to
    var glowy:GlowFilter = new GlowFilter(); //init a glow filter
    glowy.color = 0xE77471; //set a soft red color
    glowy.blurX = 3; //blur the glow
    glowy.blurY = 3;
    glowy.strength = 100; //keep standard strength value
    glowy.quality = 3; //redraw 3 times to make high quality glow
    glowy.alpha = 0.2; //set a low alpha so it doesn't look too invasive

    var blurFilter:BlurFilter = new BlurFilter(); //init a blur filter
    blurFilter.blurX = 5; //set standard blur values
    blurFilter.blurY = 5;
    var filtersArray:Array = new Array(glowy, blurFilter); //this"filterArray" stores both the blur and glow
    laserbeam1.filters = filtersArray; //assign to laser1

    laserbeam2.graphics.clear(); //clear laser2
    laserbeam2.graphics.lineStyle(4,0xF75D59); //set it to the same red color
    laserbeam2.graphics.moveTo(82,65); ///This is where we start drawing
    laserbeam2.graphics.lineTo(82 + (mouseX-82)*percent, 65 + (mouseY-65)*percent); //this is where we draw to
    laserbeam2.filters = filtersArray; //assign the same blur and glow filters
}

The comments are pretty self explanatory for most of this code, but the biggest thing to be noted is that we are passing a parameter in to the function. This “percent” is what we use to draw the progressive laser animation upon start-up.

When we call drawLaser() every frame in the main EVENT_FRAME function, we have to pass in the global percent_level so that percent has the correct value to use.  The numbers (60,65) and (82,65) that you see in my code example are the specific pixel locations of the skull eye sockets. If you’re implementing this yourself, you’ll have to manually determine those locations through some trial and error (Either that, or just use the lasers_and_smoke.fla file located at the top).

6. We have got the flash laser generation function coded up, now what we need to do is calculate the percentage for the laser beam tween effect.  We need to increment the percentage force inside enter_frame, and we also need to reset it to zero every time the mouse button is lifted, as we have to start over again.

The new code for enter_frame, therefore, looks like this:

function enter_frame (e:Event):void {
    if(mouseState){
        if(percent_level &lt; 1){ //if we don't have full power beam, crank it up
            percent_level += 0.34;
        }
        else{
            percent_level = 1; //if we do, keep it at a 1:1 ratio so it doesn't over shoot
        }
        drawLaser(percent_level); //pass the value in
    }
}

and the new mouse_up function looks like this (we also have to clear the graphics on MOUSE_UP too):

function mouse_up (e:MouseEvent):void {
    laserbeam1.graphics.clear(); //clear the laser1 graphic
    laserbeam2.graphics.clear();//clear the laser2 graphic
    percent_level = 0; //reset our charge
    mouseState = false; //turn off the boolean
}

Of course, at the very bottom of our actionscript file, we need 1 more line:

init();

 

Throwing all of this code together, and compiling your flash file via Ctrl+Enter, gives us the following laser effect in flash!

 

For the smoke effects in our flash game application, in addition to the Easter Egg collision detection, please keep on the lookout for part two of this laser and smoke effects in Flash Tutorial on flashcove.net!

 

Thanks for tuning in! (And have a Happy Flash Loaded Easter!)

(TO VIEW THE SECOND PART OF THIS TUTORIAL, GO TO THE LINK DIRECTLY BELOW!)

http://flashcove.net/577/part-2-laser-beams-and-smoke-effects-in-flash-games/

-Dave at the FlashCove (http://flashcove.net)

]]>
http://flashcove.net/496/laser-and-smoke-effects/feed/ 2
Elastic Collision Detection between Entities in Flash AS3 http://flashcove.net/452/elastic-collision-detection-and-resolution-between-entities-in-flash-as3/ http://flashcove.net/452/elastic-collision-detection-and-resolution-between-entities-in-flash-as3/#comments Sat, 23 Apr 2011 18:22:04 +0000 Dave http://flashcove.net/?p=452 Elastic Collision Detection between Entities in Flash AS3

What we have got here today is a nice simple example of some Flash AS3 physics source code! Real-time collision between several varying size and mass circles. Along with that...

]]>
Elastic Collision Detection between Entities in Flash AS3

What we have got here today is a nice simple example of some Flash AS3 physics source code! Real-time collision between several varying size and mass circles. Along with that of course, is some boundary detection to keep our floating objects in frame of view. This flash physics source code is simple to read, and easy to understand. Coming in at not even 100 lines of actionscript code, you’ll be well on your way to more advanced examples of elastic collision in applications and flash games.

Source code can be found right here:

Open up the “circle_collision.fla”, and then run it by pressing Ctrl + Enter in Flash.

And a demo of this application is here:

Now, in case you need a refresher on what “elastic collision” actually is, its a transfer of momentum between two moving (or static) objects. When the balls bounce in the flash physics demo above, they don’t just simply bounce off each other, there is actually a transfer of energy between the two. Mass has an effect on what happens, and if a tiny ball is moving incredibly fast, and collides with a nearly static large ball, the large one will get a small push, absorbing most of the energy into its mass rather than into its momentum/velocity. To achieve this flash physics effect though, is actually quite simple, and doesn’t take much more as3 code rather than implementing collision with the lack of elasticity.

With that, let’s begin.

  1. After opening up a new default 550px by 400px, AS3 file; draw a nice round circle with a thick black border (maybe stroke of 8-12). Select -> Right Click -> Convert to Movieclip, and label it as “circle”.  Before pressing okay though, check the “Export for Actionscript”! You can keep it as the default “circle” export name, we’ll be using that reference in the code.
  2. Once the circle movieclip is created, we need to convert the inner_circle as well.  Inside the “circle” movieclip, click to select the inner, colored part; and then Right Click -> Convert to Movieclip, and label it as “inner_circle”.  That specific instance of the inner_circle should be named “inner“.  This is the way we are going to reference it in the code, through circle.inner (using a pointer).
  3. Once these two embedded movieclips are successfully in your library, it is time to write the code.  No circles instances are needed on the stage, you can leave it blank.
  4. The actionscript 3 source code is actually pretty simple, just two functions and some initialization.
import flash.geom.Point;

var NUMBER_OF_CIRCLES:Number = 15;

var circle_array:Array;
var vector_array:Array;
var mass_array:Array;

The import call is so we can use the Point class for distance calculations, it allows for more optimized code, and easy distance calculation.  NUMBER_OF_CIRCLES is just a constant to tell the rest of the actionscript program how many circles we want bouncing around.

And the last thing, 3 arrays.  circle_array actually contains all of our AS3 MovieClip instances.  vector_array is multidimensional, each array index contains two values in [0] and [1]; the x and y velocities for our specific circle.  The last one, mass_array contains masses for each circle, so we know how collisions can resolve in regards to momentum transfer.

Next up is the initialization function:

function init(){
    circle_array = new Array();
    vector_array = new Array();
    mass_array = new Array();
   
    for(var i:Number = 0; i < NUMBER_OF_CIRCLES; i++){
       
        circle_array[i] = new circle();
       
        circle_array[i].width = 15 + (Math.random() * 25);
        circle_array[i].height = circle_array[i].width;
       
        circle_array[i].x = (circle_array[i].width/2) + (Math.random() * (550 - circle_array[i].width*(3/2)));
        circle_array[i].y = (circle_array[i].height/2) + (Math.random() * (400 - circle_array[i].height*(3/2)));
       
        var new_color:uint = 0x000077 * Math.random();
        new_color += 0x000088;
       
        switch(i%3){
            case 0:
                new_color = new_color << 16;
                break;
            case 1:
                new_color = new_color << 8;
                break;
        }
        //new_color = new_color << 16;
        var myColor:ColorTransform = this.transform.colorTransform;
        myColor.color = new_color;
        circle_array[i].inner.transform.colorTransform = myColor;
       
        addChild(circle_array[i]);
       
        circle_array[i].id = i;
       
        vector_array[i] = new Array(Math.random() * 10, Math.random() * 10);
        mass_array[i] = circle_array[i].width * 0.10;
    }
   
    stage.addEventListener(Event.ENTER_FRAME, circle_update);
}

Obviously, first, we need to initialize the three arrays. Once inside the loop, quite a few things happen.

First, we call the constructor for the new circle, and insert it into the array, according to the loop variable i.

Set a random width so we get variate sizes of circles (minimum 15, max 40), and set the height equal to the same since circles are equal width and height (just the diameter).

Next thing, is a random position on the screen. Of course we want to constrain it into the region of view, so that’s the reason for all the accessing of the circle’s widths and heights, so we can be also close as possible to the edge without actually crossing over.

The next portion, about color, is easily the most confusing thing.  First, I set new_color to a random value between 0×000000 and 0×000077, which, according to our RGB setup, gives us a dark blue to black color. I then add 0×000088 to the mix, setting new_color now to a medium to extremely bright blue color.  The switch case breaks our creation of circles into three discrete chunks. A set that, when divided by three, has remainder 0, 1 ,or 2.  If the remainer is zero, I’m shifting left by 16 binary bits, which gives us a value between 0×880000 and 0xFF0000 (red!). If remainder is one, I’m shifting by 8 binary bits, giving us the new range 0×008800 to 0x00FF00 (green!). If remainder is two, I don’t do anything (leave it blue!).  Set the new_color to circle_array[i].inner to actually update our inner_circle, and we’re on to the next step.

addChild(circle_array[i]) actually puts our instance of the circle on the stage so it can be seen.

We set the id of the circle to be the number it was assigned with, for cleanliness.

And then store the data for the other two arrays.  In vector array, we initialize a sub-array of length two, each containing values between 0-10. The first represents our x velocity, the second our y velocity.  As for the mass, we set it to 1/10th the radius. While the 10% is arbitrary, it keeps the consistent ratio that, the bigger the circle, the more mass it has.

Once outside of the loop, we add the ENTER_FRAME event listener to our other function, so the balls actually can be updated from frame-to-frame.

That is it for the initialization of this actionscript3 source code.

__________________________________________________________________________________________

The final function, circle_update!

function circle_update(e:Event){
   
    for(var i:Number = 0; i < NUMBER_OF_CIRCLES; i++){
        circle_array[i].x += vector_array[i][0];
        circle_array[i].y += vector_array[i][1];
       
        //bounding wall collisions
        if(circle_array[i].x + (circle_array[i].width * 0.50) >= 550){ vector_array[circle_array[i].id][0] *= -1; circle_array[i].x = 550 - circle_array[i].width * 0.50; }
        if(circle_array[i].x - (circle_array[i].width * 0.50) <= 0){ vector_array[circle_array[i].id][0] *= -1;  circle_array[i].x = circle_array[i].width * 0.50; }
   
        if(circle_array[i].y + (circle_array[i].width * 0.50) >= 400){ vector_array[circle_array[i].id][1] *= -1; circle_array[i].y = 400 - circle_array[i].height * 0.50;  }
        if(circle_array[i].y - (circle_array[i].width * 0.50) <= 0){ vector_array[circle_array[i].id][1] *= -1; circle_array[i].y = circle_array[i].height * 0.50;   }
    }
   
    //ball to ball collisions
    for(var g:Number = 0; g < NUMBER_OF_CIRCLES; g++){
        var g_pos:Point = new Point(circle_array[g].x, circle_array[g].y)
        for(var k:Number = g + 1; k < NUMBER_OF_CIRCLES; k++){
            var dist = Point.distance(g_pos, new Point(circle_array[k].x, circle_array[k].y));
            if( dist < ((circle_array[g].width * 0.50) + (circle_array[k].width * 0.50)) ){
                //they're colliding!
                //elastic response
                var mass1:Number = mass_array[g];
                var mass2:Number = mass_array[k];
                var mass_sum = mass1 + mass2;
                var velX1:Number = vector_array[g][0];
                var velX2:Number = vector_array[k][0];
                var velY1:Number = vector_array[g][1];
                var velY2:Number = vector_array[k][1];
               
                var new_velX1 = (velX1 * (mass1 - mass2) + (2 * mass2 * velX2)) / mass_sum;
                var new_velX2 = (velX2 * (mass2 - mass1) + (2 * mass1 * velX1)) / mass_sum;
                var new_velY1 = (velY1 * (mass1 - mass2) + (2 * mass2 * velY2)) / mass_sum;
                var new_velY2 = (velY2 * (mass2 - mass1) + (2 * mass1 * velY1)) / mass_sum;
               
                vector_array[g][0] = new_velX1;
                vector_array[k][0] = new_velX2;
                vector_array[g][1] = new_velY1;
                vector_array[k][1] = new_velY2;
               
                circle_array[g].x += new_velX1;
                circle_array[g].y += new_velY1;
                circle_array[k].x += new_velX2;
                circle_array[k].y += new_velY2;
            }
        }
    }
}

 

Next up for this actionscript3 source code is this update function.  Let’s go through the source in some detail.

First thing that happens in the loop is I update the position of my circle via it’s X and Y velocities. Pretty simple.

circle_array[i].x += vector_array[i][0];
circle_array[i].y += vector_array[i][1];

Next up are the boundary collisions against the four walls.  The special thing about these is that all the circles have varying radii, so we have to be picky about testing for the boundary collisions in flash.

Since the circles are indexed from their absolute center, when a ball is touching the boundary, it’s actually the x-position PLUS the radius. Once collision is detected, we simple need to reset the circle’s position to the edge (precaution in case the circle was moving extremely fast, and will thereby get pinned outside the stage), adn flip the corresponding velocity.  Flip X for the left and right walls, flip Y for the top and bottom walls. That’s it!

//bounding wall collisions
        if(circle_array[i].x + (circle_array[i].width * 0.50) >= 550){ vector_array[circle_array[i].id][0] *= -1; circle_array[i].x = 550 - circle_array[i].width * 0.50; }
        if(circle_array[i].x - (circle_array[i].width * 0.50) <= 0){ vector_array[circle_array[i].id][0] *= -1;  circle_array[i].x = circle_array[i].width * 0.50; }
   
        if(circle_array[i].y + (circle_array[i].width * 0.50) >= 400){ vector_array[circle_array[i].id][1] *= -1; circle_array[i].y = 400 - circle_array[i].height * 0.50;  }
        if(circle_array[i].y - (circle_array[i].width * 0.50) <= 0){ vector_array[circle_array[i].id][1] *= -1; circle_array[i].y = circle_array[i].height * 0.50;   }

Only thing left is our elastic collisions, the meat of this flash actionscript 3 tutorial. Since every single circle needs to view every other circle, every single frame, we need a double embedded for loop.

So, if I have 10 circles, the inner loop will run 10 times, and for the second, it will run 9 (as we don’t need to repeat test with the first ball), for the third, 8, and so on..  Giving us a final loop count of 10+9+8+7+6+5+4+3+2+1 = 55!  In general purpose, this is (n^2 + n) / 2  which, in just general asymptotic running time, is O(n^2).  Not too bad I suppose, but if you’re running this on a slower PC, you may have frame-rate issues for a large amount of colliding objects.

Before we start the second, internal for loop, we store a copy of the first circle’s position in a temporary Point object, for quick reference. Given any two circles, of any size, collision can be tested very easily.  If the distance between the two circles (from their centers) is less than the sum of circle1′s radius and circle2′s radius, they’re touching!

Once a flash entity collision is confirmed, we need to find the resulting forces and directions for each circle.  What I am following in this program is an Elastic collision setup. A nice, general purpose formula can be seen right here..

v1 is our new velocity, u1 is our old velocity, u2 is the other circle’s old velocity, and m1 and m2 are the respective masses for each.

This is the exact equation we need, but it only accounts for one dimension, of one circle. We need to do this calculation four times, for X on circle1, Y on circle1, X on circle2, and Y on circle2. But.. we have all the data needed to complete the calculations, and converting this formula to actionscript 3 code, we get the following:

//elastic response
var mass1:Number = mass_array[g];
var mass2:Number = mass_array[k];
var mass_sum = mass1 + mass2;
var velX1:Number = vector_array[g][0];
var velX2:Number = vector_array[k][0];
var velY1:Number = vector_array[g][1];
var velY2:Number = vector_array[k][1];
               
var new_velX1 = (velX1 * (mass1 - mass2) + (2 * mass2 * velX2)) / mass_sum;
var new_velX2 = (velX2 * (mass2 - mass1) + (2 * mass1 * velX1)) / mass_sum;
var new_velY1 = (velY1 * (mass1 - mass2) + (2 * mass2 * velY2)) / mass_sum;
var new_velY2 = (velY2 * (mass2 - mass1) + (2 * mass1 * velY1)) / mass_sum;
               
vector_array[g][0] = new_velX1;
vector_array[k][0] = new_velX2;
vector_array[g][1] = new_velY1;
vector_array[k][1] = new_velY2;

 

Now, that last part where we actually update positions again, a second time in the frame, we need to do this to prevent the circles from “sticking” to each other.  If both balls are heading the same direction and collide, and we don’t update position a second time, there’s a much higher chance that the circles will end up overlapping, bouncing around the screen together and clumped, which looks bad.  We separate them by an extra boost to help prevent this output. To see what I’m talking about, remove those couple lines of code, and check it out in the flash tutorial demo.

 

Once more line of code though before you can compile, you need to actually call the initialization function!

 init();

At that, we are officially done!  The background art was something I just quickly sketched for presentation, and instead of a black ring around the circles, I’ve got a glowy gradient. But I’ll leave that to you guys (or just steal it from the source lol).

This type of physics is perfect for a bouncy type flash game, or maybe a pool flash game. All you’d need to do is change the art,  fire velocities only on hitting the cue ball, etc.. and of course a points system.

I hope you enjoyed this collision detection flash tutorial, and also hope you like the free actionscript3 source code.

 

-Dave at the Flash Cove (http://flashcove.net)

 

]]>
http://flashcove.net/452/elastic-collision-detection-and-resolution-between-entities-in-flash-as3/feed/ 1