Tuesday, November 2, 2010

Putting a PayPal Donation Button In Flash

This was a real mysterious one but I think I figured it out.

Here is the code for donating a fixed amount. This option adds an item at the dollar amount you set to the PayPal cart:

var variables:URLVariables = new URLVariables();
variables.cmd = "_cart";
variables.add = "1";
variables.amount = String(  TOTAL DOLLAR AMOUNT HERE  );
variables.business = "  YOUR PAYPAL EMAIL HERE  ";
variables.item_name = "Item 1";
variables.item_number = "123456789";
variables.tax = "0";
variables.currency_code = "USD";
variables.page_style = "PayPal";
variables.no_shipping = "0";
variables.undefined_quantity = "1";
variables.rn = "1";
variables.shipping = "0";
variables.shopping_url = "http://www.salvationarmyusa.org";
var request:URLRequest = new URLRequest("https://www.paypal.com/cgi-bin/webscr");
request.method = URLRequestMethod.POST;
request.data = variables;
navigateToURL(request, "_self");

Here is the code for donating an amount decided by user:

var variables:URLVariables = new URLVariables();
variables.cmd = "_donations";
variables.add = "1";
variables.business = "YOUR PAYPAL EMAIL GOES HERE";
variables.item_name = "Donation to Salvation Army";
variables.item_number = "123456789";
variables.tax = "0";
variables.currency_code = "USD";
variables.page_style = "PayPal";
variables.no_shipping = "0";
variables.undefined_quantity = "1";
variables.rn = "1";
variables.shipping = "0";
variables.shopping_url = "http://www.salvationarmyusa.org";
var request:URLRequest = new URLRequest("https://www.paypal.com/cgi-bin/webscr");
request.method = URLRequestMethod.POST;
request.data = variables;
navigateToURL(request, "_self");

And here is PayPal's description of the variables.

Monday, October 11, 2010

AS3 Shuffle Array

This reorders the elements of an array into a random order.

var anArray:Array = [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4];
anArray=shuffleArray(anArray);

function shuffleArray(arr:Array):Array{
 var arr2:Array = [];
 while (arr.length > 0){
  arr2.push(gendersArray.splice(Math.round(Math.random() * (arr.length - 1)), 1)[0]);
 }
 return arr2;
}

Wednesday, November 4, 2009

Convert a String into an Array Using Actionscript 3

I was trying to pass an array through SWFObject flashvars and realized it can't be done. Instead you need to use a string for your array, pass it into Flash , then convert it to an array using the actionscript "split" function.

//the string to turn into an array
var arrayString:String="1,2,3";

//convert the string to an array using the "," as a divider (aka delimiter)
var newArray:Array= arrayString.split(",")

//convert the array items from strings to numbers
var n=newArray.length;
while (n--) {
newArray[n]=Number(newArray[n])
}

//test: to make sure conversion to numbers worked
trace(String(trainCubesArray[0]+1)); //test: result is 2

Thursday, October 29, 2009

SWFObject Wizard Generator

This page is a wizard that lets you enter values and it creates a SWFObject embed for you.

http://www.bobbyvandersluis.com/swfobject/generator/index.html

Detecting when mouse leaves stage

This is how you detect if the mouse leaves Flash and rolls over to web page:
stage.addEventListener( Event.MOUSE_LEAVE, mouseLeaveListener );
Additionally you can also tell when the flash movie gains and loses focus, which you couldn't do in AS 2, by listening for Event.ACTIVATE and Event.DEACTIVATE.

Here is some code that detects enter/exit. Just paste into main timeline, compile, then view embedded in an html page:

//draw a box for demonstration purposes
var c:Sprite = new Sprite();
c.graphics.beginFill(0xFF);
c.graphics.drawRect(0, 0, 200, 200);
addChild(c);

//NOTE this only works embedded in a web page
//detect mouse leaving flash and rolling over web page
stage.addEventListener(Event.MOUSE_LEAVE, cursorHide);

//there is no mouse exit so you need to use this
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);

function cursorHide(evt:Event):void {
c.alpha=.2
}


function cursorFollow(evt:MouseEvent):void {
c.alpha=1
evt.updateAfterEvent();
}

Wednesday, August 5, 2009

Link navigateToURL that pops a new window with dimensions


safePromo_mc.addEventListener(MouseEvent.MOUSE_DOWN, safeClick);
function safeClick(e:MouseEvent):void {
var jscommand:String = "window.open('http://www.adobe.com','win','height=200,
width=300,toolbar=no,scrollbars=yes');";
var url:URLRequest = new URLRequest("javascript:" + jscommand + " void(0);");
navigateToURL(url, "_self");
}

Tuesday, February 24, 2009

Blur Using AS3

var blur:BlurFilter = new BlurFilter();
blur.blurX=20;
blur.blurY=20;
blur.quality=BitmapFilterQuality.LOW;
displayObjectToBlur_mc.filters=[blur];

Monday, February 9, 2009

AS3 full screen mode

Heres a function to toggle full screen mode using AS3. Note that in fullscreen mode that only the "non-printing" keys work (arrows, shift, etc).

function toggleFullScreenMode(e:MouseEvent):void {
if (viewingFullScreen==false) {
viewingFullScreen=true;
navsNorthMultiPage_mc.tween_mc.eastButtons_mc.fullScreenAnim_mc.gotoAndPlay("full");
navsSouthMultiPage_mc.tween_mc.eastButtons_mc.fullScreenAnim_mc.gotoAndPlay("full");
stage.displayState="fullScreen";
} else {
viewingFullScreen=false;
navsNorthMultiPage_mc.tween_mc.eastButtons_mc.fullScreenAnim_mc.gotoAndPlay("out");
navsSouthMultiPage_mc.tween_mc.eastButtons_mc.fullScreenAnim_mc.gotoAndPlay("out");
stage.displayState="normal";
}
}

Friday, December 19, 2008

AS3 Disable Yellow Tab Rectangles

Are you wondering why when you hit tab in your Flash site you get those nasty yellow rectangles around your links? Here's how to disable them:

If you have a movieclip with a bunch of buttons inside it and you want to disable all of them with one line of code use this:
MC_Container_Name.tabChildren = false;


Or to just disable the yellow box on a single movieclip use this:
MC_Name.tabEnabled = false;

AS3 Smooth Loaded Bitmaps

Loaded bitmaps (jpgs, pngs, etc) look bad in flash when scaling unless you smooth them. This function seems to replicate the bitmap "smoothng" setting in the library pallette. I still see tons of FLash sites out there that arent aware of this awesome setting. It makes bitmaps look great when they scale.


//create a new loader object and put it on the stage
var slideLoader:Loader=new Loader();
this.addChild(slideLoader);

//load picture into loader object
slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, scaleContentForPicture);
slideLoader.load(new URLRequest("images/tree.jpg"));

//smooth it once loaded
function scaleContentForPicture() {
var smoother_bm=Bitmap(slideLoader.content);
smoother_bm.smoothing=true;
}

Monday, December 15, 2008

Slideshow with autoplay and reset delay

This code starts with a long pause then starts looping through images. If the user interacts with the slideshow, the timer is reset then starts playing again later if the user hasnt interacted.



//setup---------------------------------------------
var resetTime:uint=5000;
var pauseBetweenSlides:uint=5000;
var slideCounter:uint=1;
var prevSlide:uint=0;

var startShowTimer:Timer=new Timer(resetTime,1);
startShowTimer.addEventListener(TimerEvent.TIMER, setUpTimer);
var slideShowTimer:Timer=new Timer(pauseBetweenSlides,0);
slideShowTimer.addEventListener(TimerEvent.TIMER, autoAdvance);

//auto advance
function autoAdvance(e:TimerEvent):void {
nexttSlide();
}

//next
function nexttSlide():void {
prevSlide=slideCounter;
slideCounter++;
if (slideCounter==6) {
slideCounter=1;
}
goToSlide();
}
//prev
function prevvSlide():void {
prevSlide=slideCounter;
slideCounter--;
if (slideCounter==0) {
slideCounter=5;
}
goToSlide();
}
//display next slide and hide previous
function goToSlide():void {
slideshow_mc["slide"+slideCounter+"_mc"].gotoAndPlay("show");
if (prevSlide>0) {
slideshow_mc["slide"+prevSlide+"_mc"].gotoAndPlay("hide");
}
}
//pause slideshow and reset timer
function resetTimer():void {
slideShowTimer.stop();
startShowTimer.reset();
startShowTimer.start();
}
//called when reset pause is finished
function setUpTimer(e:TimerEvent):void {
startShowTimer.reset();
slideShowTimer.start();
}


resetTimer();
goToSlide();


//Controls--------
function showControls():void {
slideShowPrev_mc.gotoAndPlay("show");
slideShowNext_mc.gotoAndPlay("show");
}
function hideControls():void {
slideShowPrev_mc.gotoAndPlay("hide");
slideShowNext_mc.gotoAndPlay("hide");
}



slideShowNext_mc.addEventListener(MouseEvent.CLICK, invokeNextSlide);
function invokeNextSlide(e:MouseEvent):void {
resetTimer();
nexttSlide();
}
slideShowPrev_mc.addEventListener(MouseEvent.CLICK, invokePrevSlide);
function invokePrevSlide(e:MouseEvent):void {
resetTimer();
prevvSlide();
}

Mouse enter and leave a movieclip using the Point object

Detect mouse entering and exiting a movieclip. Using this will allow rollover/out fuctionality without messing up mouse interaction of nested clips.


slideshow_mc.arrowsHotspots_mc.addEventListener(Event.ENTER_FRAME, watchForMouseEntry);
var point1:Point=new Point(0,0);
var mouseAlreadyInside:Boolean=false;
function watchForMouseEntry(e:Event):void {
point1.x=mouseX;
point1.y=mouseY;
var hs:Object=e.target;

if (hs.hitTestPoint(point1.x,point1.y,true)) {
if (mouseAlreadyInside==false) {
mouseAlreadyInside=true;
showControls()
}
} else {
if (mouseAlreadyInside==true) {
mouseAlreadyInside=false;
hideControls()
}
}
}

Thursday, November 20, 2008

Loading external images and reacting to load complete and smoothing bitmap

var slideLoader:Loader=new Loader();
csHostRef.addChild(slideLoader);

slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, slidePreloaded);
slideLoader.load(new URLRequest(xml.slide[currentSlide].mediaURL));

function slidePreloaded(){
//do stuff here now that pict has loaded

//...and this will smooth the bitmap so it doesnt look crappy scaling
var smoother_bm=Bitmap(slideLoader.content);
smoother_bm.smoothing=true;
}


Wednesday, November 12, 2008

Measuring the Stage in AS3

In AS2 you could measure the stage using Stage.width. in AS3 things are different.

In AS3 stage.width works BUT it gives you the measurement of all the items in the stage - not the width of the player window.

This person has an interesting workaround. Basically you create an empty movieclip, convert it to a Stage, then measure it. Because there is nothing in it, it measures what it can, so measures the player window!

At least that is how I understand it. Here is the code:

var myMC:MovieClip = new MovieClip();
addChild(myMC);
var _stage:Stage = myMC.stage;


Then you use this to get the measurement:

_stage.stageWidth


This even works in SWFs that are loaded in a parent shell SWF.

Thursday, November 6, 2008

Simple AS3 Video FLV Player

Here are the basics for loading an external FLV and reading progress.
var vid:Video=new Video(320,240);
videoPlayerHost.addChild(vid);

var nc:NetConnection=new NetConnection ;
nc.connect(null);

var ns:NetStream=new NetStream(nc);
vid.attachNetStream(ns);

var infoContainer:Object;
var listener:Object=new Object ;
listener.onMetaData=function(info:Object):void {
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
tmrDisplay.start();
infoContainer=info;
};
ns.client=listener;
ns.play("myVideo.flv");

var tmrDisplay:Timer=new Timer(10);
tmrDisplay.addEventListener(TimerEvent.TIMER,updateDisplay);
var playbackPercentComplete:Number=0;

function updateDisplay(e:TimerEvent):void {
playbackPercentComplete=ns.time/infoContainer.duration;
trace("PLAYING... elapsed time="+ns.time+", video length="+infoContainer.duration+", percent complete="+playbackPercentComplete);
if (ns.time>infoContainer.duration) {
playbackPercentComplete=0;
tmrDisplay.stop();
trace("done playing")
}
}

//ns.pause() will pause the video
//ns.resume() will resume the video
//ns.seek(0) will jump the playhead to the beginning

Wednesday, November 5, 2008

Simple AS3 Button Click

visit_btn.addEventListener(MouseEvent.CLICK, visit);
function visit(e:MouseEvent):void {
var request:URLRequest=new URLRequest("http://www.thrillbilliestrailer.com");
navigateToURL(request, "_self");
}

Monday, November 3, 2008

Creating Dynamic Tween Variables In a Timed Sequence

Say you want to have a number of tweens perform in a sequence but you don't want to type out all the tweens. Here is how you do it using a timer to animate some menus one at a time with a delay of 50 milliseconds between each:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

var timerCounter:uint=0;
var theTimer:Timer=new Timer(50,6);/
theTimer.start();
theTimer.addEventListener(TimerEvent.TIMER, display);

function display(e:TimerEvent):void {
timerCounter++;
var thisLoopNode:Object=menu_mc.getChildByName("node"+timerCounter);
this["tweenx"+timerCounter]=new Tween(thisLoopNode,"x",Regular.easeOut,0,100,1,true);
this["tweeny"+timerCounter]=new Tween(thisLoopNode,"y",Regular.easeOut,0,timerCounter*10,1,true);
this["tweenalpha"+timerCounter]=new Tween(thisLoopNode,"alpha",Regular.easeOut,0,1,1,true);
}

Thursday, October 30, 2008

Tweening in AS3 Part II

import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

var myTween:Tween=new Tween(test_mc,"x",Elastic.easeOut,0,300,3,true);

myTween.addEventListener(TweenEvent.MOTION_CHANGE,checkPos);
function checkPos(tevt:TweenEvent):void {
trace(test_mc.x);
}
myTween.addEventListener(TweenEvent.MOTION_FINISH,finished);
function finished(tevt:TweenEvent):void {
trace("done");
}

Wednesday, October 29, 2008

Calling Parent Variables and Functions from a Loaded SWF

Let's say I have one SWF (child.swf) that I want to load into another SWF (parent.swf), then I want to call a function that is in parent.swf from the child.swf. In AS2 you could just do _parent._parent as many times as needed to reach up the tree to get to the parent's top level. In AS3 you need to use this code below instead. Put it inside the child.swf. I have no idea what this line of code means, but is magic:
MovieClip(parent.parent).ParentFunction();
...then this sample code goes inside the parent.swf on its main timeline:
//this sample code loads the external SWF into the Parent SWF
var indexSwfRequest:URLRequest = new URLRequest("index.swf");
var indexSwfLoader:Loader = new Loader();
indexSwfLoader.load(indexSwfRequest);
addChild(indexSwfLoader);
//This is the parent function that can be called from the command that is inside the child.swf
function ParentFunction():void{
trace("It worked!");
}

Thursday, October 23, 2008

Tweening in AS3

This uses the built-in Tween and easing classes. I don't like juggling external classes from 3rd parties if I can help it.

//Tweens wont work without these:
import fl.transitions.Tween;
import fl.transitions.easing.*;

//This creates the tween
var myTween:Tween;
myTween = new Tween(movieclip, "x", Elastic.easeInOut, start, end, 3, true);

/*
The stuff in parentheses...
1. The movieClip to tween
2. Property to tween
3. Type of tween (see help: fl.transitions.easing). Here are the options:
First item: Back, Bounce, Elastic, None, Regular, Strong
Second Item aftyer period: easeIn, easeOut, easeInOut
4. Start value
5. End value
6. true=Measure in seconds, false=Measure in milliseconds.
*/

Saturday, July 26, 2008

Global Variables AS3

STEP 1. Make a class called "GlobalVarContainer.as":

package
{
public class GlobalVarContainer
{
public static var vars:Object = [];
}
}

STEP 2. Main timeline:
import GlobalVarContainer;
var currentNav:Number;
GlobalVarContainer.vars.currentNav=10;

STEP 3. Then from any clip (even loaded ones):
var currentNav2:Number=GlobalVarContainer.vars.currentNav;
trace(currentNav2);

Loading external variables from html

This brings a var in from html that is a string and converts it to a number.

var allFlashVars:Object = LoaderInfo(this.root.loaderInfo).parameters;
var currentNav:String;
var theLoadedVar:Number=Number(allFlashVars.currentNav);

Tuesday, July 22, 2008

Timer

var theTimer:Timer=new Timer(1000, 0);//(delay, zero is infinite, or any other number is the repeat count)
theTimer.start();
theTimer.addEventListener(TimerEvent.TIMER, proceed);
theTimer.addEventListener(TimerEvent.TIMER_COMPLETE, done); //when done with all repeats (not possible here because of zero)
}
function proceed(e:TimerEvent):void {
trace("tick every second");
}
function done(e:TimerEvent):void {
trace("done");
}

rollover mouseover

theSpark.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
theSpark.addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);

function enterFrameHandler(e:Event):void {
}
function rollOverHandler(e:MouseEvent):void {
}

as3 getURL

var request:URLRequest = new URLRequest("http://www.google.com");
navigateToURL(request, "_self");

Random Number between 1 and 20

Math.ceil(20*Math.random())

Thursday, July 3, 2008

Assigning a Single Class to Multiple Library Symbols

So, in AS2 I used to use one single class with multiple different library items (for example, if you were creating an asteroid field and you had multiple asteroid symbols in your library, but wanted them all to behave the same using one single class). In AS3 if you try this, you get an error: "Please enter a unique class name that is not associated with other library symbols".

I finally came across a forum that had a simple elegant answer. In the Library/Linkage you simply put the name of your class into the Base Class field instead of the Class field. 

So I tried that, and I still got an error and after tinkering a bit, I realized that something also needed to be in the Class field for everything to work. If you leave the Class filed blank, you will get the same error quoted above. To fix this, just type anything into the field. When you click OK to leave the Linkage dialog, flash will warn you that the gobbldygook you typed into the Class field doesnt exist as a class - but just ignore it. 

You should now be able to have multiple different symbols using the same class. Just do the above for each item in the library.


Monday, May 26, 2008

AS3 _parent?

_parent no longer exists in as3. It is now parent and you have to tell flash that its a MovieClip (2 examples):

MovieClip(this.parent).gotoAndPlay("reveal");
MovieClip(this.parent.parent).gotoAndPlay("main");
Great articles that explain it all:
http://www.zeuslabs.us/2007/07/12/disabling-actionscript-3-strict-mode-in-flash-cs3/
http://curtismorley.com/2007/06/13/flash-cs3-flex-2-as3-error-1119/

Friday, May 9, 2008

Sort Display List Objects Based on Y Depth

Thanks to the example on this page:

http://www.senocular.com/flash/tutorials/as3withflashcs3/?page=2

function sortChildrenByY(container:MovieClip):void {
var i:int;
var childList:Array = new Array();
i = container.numChildren;
while(i--){
childList[i] = container.getChildAt(i);
}
childList.sortOn("y", Array.NUMERIC);
i = container.numChildren;
while(i--){
if (childList[i] != container.getChildAt(i)){
container.setChildIndex(childList[i], i);
}
}
}

sortChildrenByY(this);

AS3 Way to AttachMovie

MovieClip:

var ball_mc:BallInLibrary = new BallInLibrary();
addChild(ball_mc);
ball_mc.x=100;
ball_mc.y=100;
Button:

var button_mc:ButtonInLibrary = new ButtonInLibrary()
addChild(button_mc)
button_mc.x=200;
button_mc.y=200;

AS3 Links

Yikes! Actionscript 3.0 will be very different! Here are some links: