June 8, 2009

ActionScript 3 – Dynamic Menu

Filed under: Flash, Freebies — Tags: , , , — admin @ 11:48 pm

Download Source

Here I’ll be showing you how to create a menu in Flash that creates a navigation structure from an XML file. Each button can load various types of media (images, swfs, videos) or even open a web page. We will open Flash and create a new Movie Clip called “nav” and give it the same linkage id class name. Create a a box 40px tall and convert it to a Movie Clip with the instance name of “bg”. Create a new layer and create a new dynamic text field with the instance name of “title_txt”. Make sure to embed your fonts for your desired character set. Now here is one thing I figured out that is kind of important. Create another layer on top and copy your MC called “bg” and paste it into this new layer with the instance name of “trans” and set the Alpha property to zero. This will act as our hit state. Without this the cursor loses focus when it is located over the dynamic text.

Create a class file called “BuildMenu.as”. In Flash, change your Document Class to BuildMenu. Save.

Create an XML file called “menu.xml” and fill it with these contents:

<?xml version="1.0" encoding="utf-8"?>
<navigation>
	<button title="Image" action="image1.jpg" />
	<button title="Video F4V" action="video1.f4v" />
	<button title="Video MPEG" action="video2.mpeg" />
	<button title="SWF File" action="swf1.swf" />
	<button title="Contact" action="http://www.google.com" />
</navigation>

Open BuildMenu.as and fill it with this code:

// ActionScript file
package {
	import fl.transitions.Tween;
	import fl.transitions.easing.*;
 
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
 
	public class BuildMenu extends Sprite {
 
		private var titles:Array = new Array();
		private var actions:Array = new Array();
		private var total:uint = 0;
		private var xmlFile:String = "menu.xml";
		private var loadMenuXML:URLLoader = new URLLoader();
		private var fadeSpeed:Number = 0.2;
 
		public function BuildMenu() {
 
			var reqMenuXML:URLRequest = new URLRequest(xmlFile);
 
			loadMenuXML.addEventListener(Event.COMPLETE, parseXML);
			loadMenuXML.load(reqMenuXML);
		}
 
		private function parseXML(e:Event):void {
			var menuXML:XML = new XML(loadMenuXML.data);
 
			var container:Sprite = new Sprite();
			container.name = "container";
			container.x = 100;
			addChild(container);
 
			for (var i:int = 0; i<menuXML.*.length(); i++) {
				titles.push(menuXML.button[i].@title);
				actions.push(menuXML.button[i].@action);
				var btn:MovieClip = new nav;
				container.addChild(btn);
				btn.y = i*40;
				btn.title_txt.htmlText = titles[i];
				btn.trans.addEventListener(MouseEvent.CLICK, navClick);
				btn.trans.addEventListener(MouseEvent.ROLL_OVER, fadeDown);
				btn.trans.addEventListener(MouseEvent.ROLL_OUT, fadeUp);
				btn.trans.buttonMode = true;
				btn.trans.ID = i;
			}
 
		}
 
		private function fadeDown(e:Event):void {
			var fDown:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 0.5, fadeSpeed, true);
		}
		private function fadeUp(e:Event):void {
			var fUp:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 1, fadeSpeed, true);
		}
		private function navClick(e:Event):void {
			determineLink(e.currentTarget.ID);
		}
 
		private function determineLink(id) {
			//trace(titles[id]+" -> "+actions[id]);
			var actionItem:String = actions[id].toString();
			// Find file extension
			var fileExtension:String = actionItem.substr(0,4);
			if (fileExtension == "http") {
				// this is a URL
			} else {
				fileExtension = actionItem.substr(actionItem.lastIndexOf('.')+1, actionItem.length);
				// this is a file extension
			}
			var mediaType:String = fileExtension.toLowerCase();
			switch (mediaType) {
				case "http":
				trace("Open URL -> "+actionItem);
				openURL(actionItem);
				break;
				case "flv":
				case "f4v":
				case "mov":
				case "mpeg":
				case "mp4":
				trace("Load video -> "+actionItem);
				loadVideo(actionItem);
				break;
				case "jpg":
				case "gif":
				case "jpeg":
				case "png":
				trace("Load image -> "+actionItem);
				loadImage(actionItem);
				break;
				case "swf":
				trace("Load swf -> "+actionItem);
				loadSWF(actionItem);
				break;
				default :
				trace("Incorrect file type used");
				break;
			}
		}
 
		private function loadImage(file) {
			// load Image
			var assetLoader:Loader = new Loader();
			addChild(assetLoader);
			assetLoader.load(new URLRequest(file));	
		}
 
		private function loadSWF(file) {
			// load SWF
			var assetLoader:Loader = new Loader();
			addChild(assetLoader);
			assetLoader.load(new URLRequest(file));
		}
 
		private function loadVideo(file) {
			// load Video
		}
 
		private function openURL(url) {
			// open URL
			var loadURL:URLRequest = new URLRequest(url);
			try {
				navigateToURL(loadURL, "_blank");
			} catch (e:Error) {
				trace("Cannot load -> "+url);
			}
		}
	}
}

To view the output, Test Movie in Flash.

February 26, 2009

ActionScript 2 – Find File Extension

Filed under: Flash, Freebies — Tags: , , — admin @ 10:25 pm

Let’s say we have a scenario where we have an XML file that contains references to files that are mixed media types and our Flash file will conduct a certain operation based on the file’s extension. You could structure your XML like this:

<asset url="movie.flv" type="movie" />
<asset url="image.jpg" type="image" />

But type=”movie” isn’t quite so user-friendly and has the possibility for mistakes. What would be better is this:

<asset url="movie.flv" />
<asset url="image.jpg" />

We are going to have a little ActionScript to find out what the file extension is.

*edit* – New code recommended by Luiz Fernando – Thanks! Your’s works much better!

var file:String = "movie.flv";
var fileExtension:String = file.substr(file.lastIndexOf('.')+1, file.length-file.lastIndexOf('.'));
trace(fileExtension);
// output --- flv

From here you’d want to run some checks for the file types you wish to support and run some code to showcase different types of media content.

loadAsset(file, fileExtension);
 
function loadAsset(asset, fileType) {
	var cleanFileType:String = fileType.toLowerCase();
	switch(cleanFileType) {
		case "jpg" :
		case "png" :
		case "jpeg" :
		case "gif" :
		// load image; (asset)
		break;
		case "swf" :
		// load swf; (asset)
		break;
		case "flv" :
		case "f4v" :
		case "mp4" :
		// load video (asset)
		break;
	}
}

February 9, 2009

Freebie: ActionScript 3 – Flash text using XML & CSS

Filed under: Flash, Freebies — Tags: , , , , , — admin @ 4:39 pm

Download Source

Ok, so I’m a little behind the curve in AS3 right now. But I’ve gotta get learning because I see a lot of AIR apps and other AS3 apps I need to build in the future. I’ve a had a little spare time today to follow Colin Moock’s Essential AS3 book. I’ve made it a goal to create a file that uses an ActionScript 3 class to load external text stored in an XML file that is styled with a CSS file.

myText.xml

<?xml version="1.0" encoding="utf-8"?>
<MYTEXT>
	<TEXT><![CDATA[<p><span class='bigText'>This is my title</span></p><br /><p><b>Bold</b>, <i>italics</i>, <u>underline</u>, normal</p><br /><p><a href='http://www.google.com/'>Web link</a></p><br /><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque facilisis, metus ut commodo tempus, enim mi placerat justo, nec ornare sapien urna eu nisl. In hac habitasse platea dictumst. Integer suscipit, nisl id consectetur pharetra, velit quam accumsan diam, sit amet commodo nibh libero vitae neque. Donec neque dui, ultrices id, condimentum in, eleifend non, odio. Sed elit risus, hendrerit at, gravida quis, porttitor a, nisi. Pellentesque ullamcorper. Nulla facilisi. Maecenas sagittis. Phasellus nulla ipsum, varius non, bibendum vel, sollicitudin ac, nunc.</p><p>Integer id tortor sit amet odio fermentum dictum. Integer metus arcu, laoreet non, lobortis et, tincidunt sed, erat. Quisque porttitor nibh ac felis. Donec facilisis, purus sed eleifend dapibus, quam est ultrices turpis, vel dictum justo lectus ac ligula. Nullam diam tortor, suscipit sodales, porta at, vestibulum venenatis, ipsum. Nunc placerat, urna eu elementum dictum, odio metus lobortis justo, sit amet convallis lacus mauris sed sem.</p>]]></TEXT>
</MYTEXT>

styles.css

p {
	font-family: Arial;
	font-size: 12px;
	color: #006600;
}
.bigText {
	font-family: Arial;
	font-size: 24px;
	color: #0099FF;
	letter-spacing:-1px;
}
a {
	color:#FF0000;
	text-decoration:none;
}
a:hover {
	color:#0000FF;
	text-decoration:underline;
}

CSS_XML.as

package {
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import flash.net.*;
 
	public class CSS_XML extends Sprite {
 
		private var myText:XML;		
		private var urlLoaderXML:URLLoader;
		private var paragraph:String;
		private var CSSFile:String = "styles.css";
		private var XMLFile:String = "myText.xml";
 
		public function CSS_XML() {
			var urlRequest:URLRequest = new URLRequest(XMLFile);
			urlLoaderXML = new URLLoader();
			urlLoaderXML.addEventListener(Event.COMPLETE, completeListenerXML);
			urlLoaderXML.load(urlRequest);
		}	
 
		private function completeListenerXML(e:Event):void {
			myText = new XML(urlLoaderXML.data);
			paragraph = myText.TEXT.toString();
			loadCSS();
		}
 
		private function loadCSS() {
			var urlLoaderCSS:URLLoader = new URLLoader();
			urlLoaderCSS.addEventListener(Event.COMPLETE, completeListenerCSS);
			urlLoaderCSS.load(new URLRequest(CSSFile));
		}
 
		private function completeListenerCSS(e:Event):void {
			var styleSheet:StyleSheet = new StyleSheet();
			styleSheet.parseCSS(e.target.data);
			var t:TextField = new TextField();
			t.multiline = true
			t.autoSize = TextFieldAutoSize.LEFT;
			t.width = 550;
			t.wordWrap = true;
			t.styleSheet = styleSheet;
			t.htmlText = paragraph;
 
			addChild(t);
		}
	}
}

Now the end-result isn’t amazing-looking. It definitely needs a scrolling utility, but it’s a good start.

Enjoy!

February 5, 2009

Freebie: Flash MouseWheel Scrolling (AS2+XML)

Filed under: Flash, Freebies, Photoshop — Tags: , , , , , — admin @ 11:20 pm

This is something I’ve been wanting to figure out for a while and just now had time to take it on. In this example we’re scrolling text in a MovieClip that uses a traditional scrollbar and the MouseWheel. MouseWheel scrolling only occurs while the mouse is hovering over the text area. If you use this and resize those components, you won’t need to edit any of this. It’ll know what to do, trust me. ;)

Download Source View Example

This is the meat of the code that runs the scroller. The text info populates target_mc.main_txt. Invoke scrollInfo() to start the scrolling.

import mx.transitions.Tween;
import mx.transitions.easing.*;
 
track_mc._visible = false;
drag_mc._visible = false;
 
mouseListener = new Object();
 
function scrollInfo() {
	// If scrolling is not needed, hide scrolling assets
	track_mc._visible = false;
	drag_mc._visible = false;
	// Find height of the target_mc
	var clipheight:Number = target_mc._height;
	// Find y position of target_mc
	var starty:Number = 0;
	target_mc._y = 0;
	// Find height of mask over target_mc
	var maskheight:Number = mask_mc._height;
	// Limit scrolling
	var maxscroll:Number = maskheight-clipheight+starty;
	// Start dragging position
	var startposition:Number = drag_mc._y=track_mc._y;
	// Find y position of scrollbar face
	var startdragT:Number = drag_mc._y;
	// Limit var for scrollbar face
	var startdragB:Number = track_mc._height-drag_mc._height+track_mc._y;
	// Calculation for scrolling clip
	var diff:Number = (clipheight-maskheight)/(track_mc._height-drag_mc._height);
	// Var for activating the MouseWheel scrolling
	var mScroll:Boolean = false;
	// Disable all this if scrolling isn't necessary
	if (target_mc._height<mask_mc._height) {
		track_mc._visible = false;
		drag_mc._visible = false;
		mScroll = false;
		mouseWheelScroll();
	} else {
		track_mc._visible = true;
		drag_mc._visible = true;
		mScroll = true;
		mouseWheelScroll();
	}
	// drag_mc on press
	drag_mc.onRollOver = function() {
		this.gotoAndPlay("start");
	};
	drag_mc.onRollOut = function() {
		this.gotoAndPlay("end");
	};
	drag_mc.onPress = function() {
		// Start dragging, limit the dragging to parameters
		startDrag(this, false, this._x, track_mc._y, this._x, (track_mc._height+track_mc._y)-this._height);
		// Update scrolling clip in conjunction with the y position of the drag_mc
		this.onMouseMove = function() {
			difference = Math.abs(startposition-this._y);
			target_mc._y = -Math.round(difference*diff+starty);
		};
	};
	// On release, kill function
	drag_mc.onRelease = function () {
		stopDrag();
		delete this.onMouseMove;
	};
	drag_mc.onReleaseOutside = function () {
		stopDrag();
		this.gotoAndPlay("end");
		delete this.onMouseMove;
	};
	// Mouse Wheel Scrolling
	function mouseWheelScroll() {
		mouseListener.onMouseWheel = function(delta) {
			// Only do it if the mouse is hovering over the text area
			if (_xmouse > mask_mc._x && _xmouse < mask_mc._x+mask_mc._width && _ymouse > mask_mc._y && _ymouse < mask_mc._y+mask_mc._height) {
				if (delta<0 && mScroll == true) {
					if (target_mc._y>maxscroll+20) {
						target_mc._y += delta*10;
					} else {
						target_mc._y = maxscroll;
					}
				}
				if (delta>0 && mScroll == true) {
					if (target_mc._y<starty-20) {
						target_mc._y += delta*10;
					} else {
						target_mc._y = starty;
					}
				}
				drag_mc.gotoAndPlay("end");
			}
			// Move the scroll button to correspond with the position of the text (this was the hard part)
			difference = Math.abs(startposition-target_mc._y);
			var mT:Tween = new Tween(drag_mc, "_y", Regular.easeOut, drag_mc._y, difference/diff+starty, 0.2, true);
		};
		Mouse.addListener(mouseListener);
	}
}

Use it however you want, Enjoy!

© 2010 Aaron Benson. All rights reserved.

Powered by WordPress