Thursday, July 03, 2008

Visit my new Actionscript 3 blog

I will no longer be adding to this blog because I have started a new blog for Actionscript 3: http://mattmaxwellas3.blogspot.com/

I will still leave this blog up because it contains valuable info for AS2.

Friday, January 18, 2008

Mouse Wheel Scroll

var mouseListener:Object = new Object();
mouseListener.onMouseWheel = function(delta) {
trace(delta/3);
//result is 1 for up and -1 for down
}
Mouse.addListener(mouseListener);

Wednesday, January 16, 2008

Drag Clock Hands in Circular Motion

Thanks Dave Stiller for this snippet. His instructions are here.

mcMinute.onPress = function() {
this.onMouseMove = function() {
var angle:Number = Math.atan2(
mcFace._ymouse - mcFace._height / 2,
mcFace._xmouse - mcFace._width / 2
);
this._rotation = (angle * 180 / Math.PI) + 90;
};
};
mcMinute.onRelease = function() {
delete this.onMouseMove;
};
mcMinute.onReleaseOutside = mcMinute.onRelease;

Wednesday, December 26, 2007

Substrings

This gets the fifth character out of myName. The first number is the beginning, the second is the end. It is sort of like selecting text from a start point to an end point.

myName.substring(4, 5)

Thursday, December 20, 2007

Local to Global

Here's how to take nested x and y and convert them to global x and y:

//these nested coordinates...
var myPoint:Object = {x:theClip.nestedclip._x, y:theClip.nestedclip._y};
theClip.nestedclip.localToGlobal(myPoint);
//
//are now root coordinates...
trace(myPoint.x)
trace(myPoint.y)

Sunday, September 09, 2007

Creating good FLVs

Here is a good article on reducing the file size of FLVs. My FLVs are now half the size but actually look better. The main secret was lowering the data rate to 250, having the frame rate between 12 and 15, letting the software automatically choose the keyframes, and using a mono audio track.

http://www.communitymx.com/content/article.cfm?cid=EBD77&print=true

Wednesday, August 08, 2007

Caps Lock

if (Key.isToggled(Key.CAPSLOCK)) {}

Friday, July 13, 2007

Controlling an Imported Captivate Movie

All these little widgets on my site use these variables, they are all in the Captivate help filebut I guess not many people can find them due to the amount of questions on the Captivateforum

rdcmndPrevious = 1 Is used to go back one slide in a captivate movie
rdcmndNextSlide = 1 Is used to go forward one slide in a captivate movie
rdcmndPause = 1 Is used to pause a captivate movie
rdcmndResume = 1 Is used to play a captivate movie
rdcmndRewindAndStop rewind and stop the movie
rdcmndRewindAndPlay Is used to restart and play a captivate movie
rdcmndGotoFrame Is used to go to a specific frame, note this is Frame not a Slide (see rdinfoFrameCount)
rdcmndExit does what is say's exit's the movie
rdcmndInfodisplay the information window (Yep that little Info box that everyone moans about
rdinfoFrameCount total number of swf frames in the movie (this is not the number of frames in the main Timeline, but the sum of all slide frames)
rdinfoSlidesInProject number of slides in the movie (including hidden slides)
rdinfoCurrentFrame current frame (goes from 1 to rdinfoFrameCount when you play the movie)
rdinfoCurrentSlide slide currently playing (zero based)
rdinfoSlideCount number of slides in the movie (not including hidden slides)
rdIsMainMovie can be used to identify a Captivate movie

And a couple of unpublished variables

rdcmndHidePlaybar =
is used to hide or show the playbar 1= hide 0=show
rdcmndCC =
is used to show or hide Closed Captions 1= show 0=hide
rdcmndMute =
is used to mute or unmute the audio 1= mute 0=unmute

I do not use flash as I am not clever enought to understand it, instead I use Swishmax a nice little app.
To create an external playbar in swish I would create a set of buttons then add the following script to each

Restart buttonon (release) {this._parent._parent.rdcmndRewindAndPlay = 1;}
Rewind buttonon (release) {this._parent._parent.rdcmndPrevious = 1;}
Pause buttonon (release) {this._parent._parent.rdcmndPause = 1;}
Play buttonon (release) {this._parent._parent.rdcmndResume = 1;}
Forward buttonon (release) {this._parent._parent.rdcmndNextSlide = 1;}
Exit button on (release) {fscommand("Quit","true");}

Monday, July 02, 2007

Google Analytics in an all-Flash site

Old Version:
http://www.google.com/support/googleanalytics/bin/answer.py?answer=74979

New Version:
http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55520


its very easy:
1. Get a Google analytics account

2. Give it a URL

3. Google Analytics gives you a little bit of code to embed in the HTML

4. Paste the code into your html

5. Use one line of code in flash for every click

This is a great way to do path analysis in a Flash site.

Wednesday, May 23, 2007

Getting a Blogger XML feed to work in Flash

I wrestled for about an hour because the XML from Blogger was coming up blank whenever I ran my project on the web server. This article saved me:

http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_16520

Basically I need to have "proxy.php" in the same directory as the site - with the Atom XML URL inside it. Then, in Flash I need to use "proxy.php" for the path. I think the way this works is that the PHP file reads the XML and stores it, then Flash gets the XML text from the PHP file. This code is in the Nitro Circus project in proxy.php and the "if the planet==3" area of planets.as file.

-------------

Text from Adobe:

Loading data across domains
For security reasons, a Macromedia Flash movie is not permitted to load data from a different Internet domain. Attempts to access cross-domain data or data returned to Macromedia Flash Player from another domain will be ignored by the Macromedia Flash Player. SeeAdditional information to find specific information on domain comparison.

Note: Macromedia Flash Player release 6r47 did not allow an HTML page on the web to load a SWF file that was stored on the local machine (for example on a CD-ROM or local hard drive). This functionality has been restored in Macromedia Flash Player 6 release r65 (6,0,65,0) and above. For SWF files accessing internet based content these rules still apply.

If a Flash web application needs to access information from a different domain, a developer can use one of two recommended methods on the server-side to give Flash access to this data. See the table below for an overview of each method.

Server-side proxy method
-Requirements: You must be able to upload and run a server-side script on a server in the same domain as the Flash movie.
-In this method, the Flash movie accesses the script, which loads the information, retrieves it, and returns the information back to the Flash movie.
-This method is best if the server hosting the data is not under your control (for example, a public XML feed).

1. Download and unzip or unstuff one (or all of) the following example files:
ColdFusion Example:
Windows ZIP
Macintosh SEA

PHP Example:
Windows ZIP
Macintosh SEA

ASP Example:
Windows ZIP
Macintosh SEA

Java Servlet Example:
Windows ZIP
Macintosh SEA

The above code example must be hosted from a server in the same domain as the Macromedia Flash document.
Note: Other server-side scripts can be used. Developers using other types of files can use one of the above examples as guideline.

2 . Replace the URL in the example with the URL that you want Macromedia Flash to load data from.
3 . In the Macromedia Flash movie, in the action that loads the data, point to the URL where you will post the above code example.
4 . Publish and upload both documents.

Thursday, April 19, 2007

ColorTransform (tweaking r, g, b, alpha)


//transform color +500 is blown out to white, -500 is solid black, 0 is normal
import flash.geom.ColorTransform;
import flash.geom.Transform;
var colorTrans:ColorTransform=new ColorTransform();
colorTrans.redOffset = 100;
colorTrans.greenOffset = 100;
colorTrans.blueOffset = 100;
this.transform.colorTransform = colorTrans;

Tuesday, March 20, 2007

Gradient Masks in Flash 8

Make two movieclips:

1. The "maskee" which is just a regular MovieClip containing a picture.
2. The "mask" which is also a movieClip but contains some blends that fade to a solid color to clear

maskee.cacheAsBitmap=true
mask.cacheAsBitmap=true
mask.setMask(maskee)

Monday, March 19, 2007

MovieClip Depth Property

mc.getDepth();

Remember the parens

Saturday, March 17, 2007

Call a JavaScript function from Flash

This Flash function calls a Javascript and sends a string to be displayed in an alert window.

import flash.external.*;
btn.onPress = function() {
ExternalInterface.call("playmovie", "hi Matt");
};


Put this Javascript function in the html file
function playmovie(theMessage){   
alert(theMessage)
}

Friday, March 09, 2007

sIFR

This tool uses css, flash, and Javascript to embed non-web fonts in a browser.

http://www.mikeindustries.com/sifr/

SlideShowPro

http://www.slideshowpro.net/

String Search and Replace


String.prototype.replace = function(str, rep) {
return this.split(str).join(rep);
};


//use it like this
var myStr:String = "Hello earth!"
trace(myStr.replace("earth","world")

Timer Countdown


displayTime = 10;
countDown = function () {
displayTime--;
if (displayTime == 0) {
clearInterval(timer);
}
};
timer = setInterval(countDown, 1000);

Change MovieClip Color


colorTo = function (theHex, theMc) {
colorful = new Color(theMc);
colorful.setRGB(theHex);
};
colorTo(0x00FFFF, theMc);

Wednesday, March 07, 2007

Simple Tween Equation

this._y += (newPos - this._y) * .5;

Sunday, February 18, 2007

2d, 3d Geometry Information

Game Programmers Encylopedia
2D math principles
3D math principles

Distance Between Two Points (3d)

GEN_get3DDistance = function (ax, ay, az, bx, by, bz) {
dx = ax-bx;
dy = ay-by;
dz = az-bz;
theDistance = Math.sqrt(dx*dx+dy*dy+dz*dz);
return theDistance;
};
trace(GEN_get3DDistance(5,0,0,10,0,0))

Distance Between Two Points (2d)

GEN_get2DDistance = function (ax, ay, bx, by) {
dx = ax-bx;
dy = ay-by;
theDistance = Math.sqrt(dx*dx+dy*dy);
return theDistance;
};
this.onEnterFrame = function() {
trace(GEN_get2DDistance(thing._x, thing._y, _xmouse, _ymouse));
};

Optimizing Frame Rate

http://mxdj.sys-con.com/read/142694_p.htm

Shared Object


//HIGH SCORE SHARED OBJECT =======================================
// create a new shared object named "healthfirstdental"
my_so = SharedObject.getLocal("healthfirstdental");
// set a new variable (alreadyvisited) to 0
if (my_so.data.alreadyvisited == undefined) {
my_so.data.alreadyvisited = 1;
// this saves the shared object immediately as opposed to when the swf shuts down
my_so.flush;
} else {
gotoAndStop("skipped");
}

//zeroalreadyvisited.onRelease = function() {
//my_so.clear();
//};

Parallax Function


GEN_positionInParallax = function (thisMovieClip, theBoundsMovieClip, theLeaderMovieClip) {
//
// X...
//get offset % by comparing theLeaderMovieClip with theBoundsMovieClip
extraXSpace = (theLeaderMovieClip._width)-(theBoundsMovieClip._width);
westGap = (theBoundsMovieClip._x)-(theLeaderMovieClip._x);
leaderWestGapXPercentage = westGap/extraXSpace;
//set position
followerExtraXSpace = (thisMovieClip._width)-(theBoundsMovieClip._width);
thisMovieClip._x = (-(followerExtraXSpace*leaderWestGapXPercentage))+theBoundsMovieClip._x;
//
// Y...
//get offset % by comparing theLeaderMovieClip with theBoundsMovieClip
extraYSpace = (theLeaderMovieClip._height)-(theBoundsMovieClip._height);
northGap = (theBoundsMovieClip._y)-(theLeaderMovieClip._y);
leaderWestGapYPercentage = northGap/extraYSpace;
//set position
followerExtraYSpace = (thisMovieClip._height)-(theBoundsMovieClip._height);
thisMovieClip._y = (-(followerExtraYSpace*leaderWestGapYPercentage))+theBoundsMovieClip._y;
};

Saturday, February 17, 2007

Keyboard Control


if (Key.isDown(39)) {
//LEFT;
}
if (Key.isDown(37)) {
//RIGHT;
}
if (Key.isDown(40)) {
//UP;
}
if (Key.isDown(38)) {
//DOWN);
}
if (Key.isDown(65)) {
//A;
}
if (Key.isDown(83)) {
//S;
}

Circular Plotting Function


GEN_PlotItemsOnCircle = function (numberOfItems, theRadius, startDegree) {
sliceSize = (360/numberOfItems);
theCoordinates = [];
for (i=0; i<(numberOfItems); i++) {
angle = startDegree*(Math.PI/180);
xPlot = theRadius*Math.cos(angle);
yPlot = theRadius*Math.sin(angle);
startDegree += sliceSize;
theCoordinates[i] = [xPlot, yPlot];
}
return theCoordinates;
};

Flash 3D Function


GEN_putObjectIn3dScene = function (theClip, cameraDistanceFromTracerPlane, x, y, z, vanishingPointX, vanishingPointY) {
if (z<0) {
theClip._alpha = 0;
} else {
theClip._alpha = 100;
}
var zfactor = cameraDistanceFromTracerPlane/z;
theClip._x = x*zfactor+vanishingPointX;
theClip._y = y*zfactor+vanishingPointY;
theClip._xscale = 100*zfactor;
theClip._yscale = 100*zfactor;
theClip.cacheAsBitmap();
theClip.swapDepths(Math.floor(100000-z));
};

Fuse Kit

Fuse Kit is a very nice set of classes, that when added to Flash, add a way to easily tween movieclips in tons of ways. The description below is the beginners "simpleSetup" mode only. There are a number of ways to use Fuse Kit. This is the easiest-to-understand way.

You need to first install Fuse Kit. Installing this MXP installs new classes into Flash.

Next use this code to import the classes into your code:


import com.mosesSupposes.fuse.*;
ZigoEngine.simpleSetup(Shortcuts, PennerEasing, FuseFMP);



To set a simple property for a movieClip without tweening:


my_mc.Blur_blur=20;



NOTE: To see what these cool new properties are, go to Flash Help FuseKit2.2/ mosessupposes.fuse/ Shortcuts

To set a simple property for a movieClip with tweening:


my_mc.slideTo(300, 300, 2);
my_mc.rotateTo(180, 2);
my_mc.colorTo("#ffffff", 10)
my_mc.scaleTo(10, 4)
my_mc.Blur_blurXTo(50, 1, "easeInOutElastic", 2);


Fuse Kit 2.1 also installs a cool tweening pallette into Flash. Go to Window>Other Panels>customEasingTool2 to see the tweens and even make up your own.

If you put a number in quotes, it will add or subtract the number. For example, if a movieclip._alpha = 90, using "10" in the Fuse command will tween it up from 90 to 100. Using 10 will tween the alpha to 10. See "Know your relatives" in the PDF below for a better explanation.

Here is a PDF Beginners Guide that explains the various components of Fuse.

Wednesday, October 11, 2006

SWFObject

This Javascript Flash Player detection and embed script works great. No annoying dotted line around the Flash.

http://blog.deconcept.com/swfobject/

Tuesday, August 22, 2006

ClickTAG and Flash Banner Specs

This is a great article on how to do Flash banners.

Tuesday, May 23, 2006

Depth Sorting

Use this code to sort objects in 3d space.



function sortDepthOfField(clipArray) {

clipArray.sort(clipYSort);

for (var i = 0; i<clipArray.length; i++) {
clipArray[i].swapDepths(i);
}
}
sortOnY = function(a,b){
if(a._y > b._y){
return 1;
}else if(a._y < b._y){
return -1;
}else{
return 0;
}
}
theClips = [bird1, bird2, bird3, bird4, bird5, bird6];
this.onEnterFrame = function() {
sortDepthOfField(theClips);
};

Tuesday, May 09, 2006

Shared Objects (Flash Cookies)

Here is the code to set up the shared object:
//HIGH SCORE SHARED OBJECT =======================================
// create a new shared object named "zionshighscore"
my_so = SharedObject.getLocal("zionshighscore");
// set a new variable (highScore) to 0
if (my_so.data.highScore == undefined) {
my_so.data.highScore = 0;
}
// this saves the shared object immediately as opposed to when the swf shuts down
my_so.flush;
//my_so.data.highScore = 0;
highScore_mc.highScore.text = "$"+my_so.data.highScore+".00";
// show or hide high score display
if (my_so.data.highScore == 0) {
highScore_mc._alpha = 0;
} else {
highScore_mc._alpha = 100;
}
zeroHighScore.onRelease = function() {
my_so.data.highScore = 0;
highScore_mc.highScore.text = "$"+my_so.data.highScore+".00";
};
//

This code sets the shared object to a new value:
updateHighScore = function () {
if (theScore>my_so.data.highScore) {
my_so.data.highScore = theScore;
showPrompt("New High Score!", 4000);
}
};

Popup Windows from Flash

researchTools.toolsText.link1a.onRelease = function() {
getURL("javascript:NewWindow=window.open('http://money.cnn.com/pf/features/lists/nar_3q05/','newWin','width=620,height=550,left=100,top=100, toolbar=Yes,location=No,scrollbars=Yes,status=Yes,resizable=Yes,fullscreen=No'); NewWindow.focus(); void(0);");
};

Timer

Look in the Equity Adventure code in gameplay.as

Shuffle Array

shuffleArray = function (theArray) {
// (Shuffle 10 times just for the heck of it)
for (i=0; i<10; i++) {
theArray.sort(function (a, b) {
return random(3)-1;
});
}
};




Array.prototype.shuffle = function() {
var Arr2 = new Array();
while (this.length>0) {
Arr2.push(this.splice(Math.round((this.length-1)*Math.random()), 1));
}
return Arr2;
};
theSlides=[1,2,3,4]
theSlides.shuffle();

Basic Class Structure


class Dog extends MovieClip {
var speedLimit:Number = 5;
var point:Object;
var dogState:String = "stay";
var trash:MovieClip;
function Dog() {
//constructor
}
function onEnterFrame():Void {
//enterFrame
}
private function adjustVelocity(a, b):Void {
//private function
}
}
function onRelease():Void {
//onrelease
}
function onDragOut():Void {
//ondragout
}
function onRollOver():Void {
//onrollover
}
function onRollOut():Void {
//onrollout
}

Sound Objects

For sounds to not conflict with each other, they need to be assigned to movieclips - I think. This also works:

function newLevelMusic() {
var newLevel:Sound = new Sound();
newLevel.attachSound("newLevel");
newLevel.start();
}
newLevelMusic()

Here is a function that kind of works as a sound machine:

//sfxSpeaker
playSound = function (theID, theVolume, repeatTimes) {
voiceCounter++;
sfxSpeaker.createEmptyMovieClip("newVoiceMC"+voiceCounter, voiceCounter+10);
sfxSpeaker["newVoiceMC"+voiceCounter].theSound = new Sound(sfxSpeaker["newVoiceMC"+voiceCounter]);
sfxSpeaker["newVoiceMC"+voiceCounter].theSound.attachSound(theID);
sfxSpeaker["newVoiceMC"+voiceCounter].theSound.setVolume(theVolume);
sfxSpeaker["newVoiceMC"+voiceCounter].theSound.start(0, repeatTimes);
};

Tweening Using Flash's Built In Tweens

First you need to pull in tween classes:

import mx.transitions.Tween;
import mx.transitions.easing.*;
this.lvlTween = new Tween(targetMc, "_y", Bounce.easeOut, -400, 200, 30);
tweenInstance.onMotionFinished = function() {
// ...
};

For more info, search for "Using the Tween class" in Flash help

Data.as Arrays

Here is an easy to understand array file that to me is easier than XML. This of course requires recompiling of the swf but for data that doesnt change this is nice.


//database
//leaves, timerCycles, dogsArray
var gameLeaves:Array = [];
var gameTicks:Array = [];
var gameLeafFallSpeeds:Array = [];
//level 0
gameLeaves[0] = 50;
gameTicks[0] = 600;
gameLeafFallSpeeds[0] = 15;
//level 1
gameLeaves[1] = 100;
gameTicks[1] = 800;
gameLeafFallSpeeds[1] = 15;
//level 2
gameLeaves[2] = 200;
gameTicks[2] = 1100;
gameLeafFallSpeeds[2] = 10;
//level 3
gameLeaves[3] = 300;
gameTicks[3] = 1200;
gameLeafFallSpeeds[3] = 10;
//level 4
gameLeaves[4] = 400;
gameTicks[4] = 1700;
gameLeafFallSpeeds[4] = 5;
//level 5
gameLeaves[5] = 600;
gameTicks[5] = 2100;
gameLeafFallSpeeds[5] = 5;
//level 6
gameLeaves[6] = 800;
gameTicks[6] = 2500;
gameLeafFallSpeeds[6] = 5;

#include

#include "data.as"
#include "main.as"

Display Quality

_quality = "LOW";
_quality = "MEDIUM";
_quality = "HIGH";
_quality = "BEST";

Preloading

To prevent all of the classes from loading in frame 1 (which causes an annoying blank screen for a long time before the preloader appears):
-I set them to load in a later frame (8).
-Movieclips in the library that have Classes attached to them need to have the "export in first frame" checkbox unchecked for this to work.
-For the classes to load there needs to be at least one instance on the stage somewhere in a timeline or the Class won't
load. For example, in the leaf game there are leaves that are pulled dynamically out of the library that have the "Leaf" class attached. These leaves weren't working until I realized that there was no instance of a leaf anywhere in the movie. I created an instance in "_root.leafHost.leafInit" and the leaves started working becuase they had been instantiated
by this new clip.
To preload sounds the same principles apply. There needs to be a frame with a sound attached
for attached sounds to work.
Here is some preloader code:

this.onEnterFrame = function() {
if (_framesloaded == _totalframes) {
delete this.onEnterFrame;
gotoAndStop("intro");
} else {
theProgress = "Loading "+(Math.floor(this.getBytesLoaded()/1000))+"K of "+(Math.floor(this.getBytesTotal()/1000))+"K";
preloadBar._width = (241*this.getBytesLoaded())/this.getBytesTotal();
}
};

Here is another preloader:

this.onEnterFrame = function() {
//trace("...");
preloader_mc.loaderText.text = "LOADING "+Math.floor(this.getBytesLoaded()*.001)+"K OF "+Math.floor(this.getBytesTotal()*.001)+"K";
preloader_mc.loaderBar._width=(preloader_mc.loaderBG._width*this.getBytesLoaded())/this.getBytesTotal()
if (this.getBytesLoaded() == this.getBytesTotal()) {
delete this.onEnterFrame;
gotoAndStop("titlescreen");
}
};