Actionscript 2 Sandbox

From Wikicliki
Jump to: navigation, search

the readable stuff is at the Actionscript page, the sandbox is the-messing-around-with-snippets-section.

and one math website: http://library.thinkquest.org/20991/home.html

mouse movement direction detection for as2

mousecursor is the item being flipped

checkX = function (dx, oldVal, newVal) {
	if ((_xmouse<=740) && (_xmouse>=0) && (_ymouse<=250) && (_ymouse>=0)) {
		if (oldVal<newVal) {
			trace("moving right");
			mousecursor.gotoAndStop(1);
		} else if (oldVal>newVal) {
			trace("moving left");
			mousecursor.gotoAndStop(2);
		}
		return newVal;
	}
};

// this checks for up and down but since you dont need it i am commenting this out

checkY = function (dy, oldVal, newVal) {
	if ((_xmouse<=200) && (_xmouse>=0) && (_ymouse<=200) && (_ymouse>=0)) {
		if (oldVal<newVal) {
			trace("down");
		} else if (oldVal>newVal) {
			trace("up");
		}
		return newVal;
	}
};


this.watch("xdir", checkX);
this.watch("ydir", checkY);
this.onMouseMove = function() {
	xdir = _xmouse;
	ydir = _ymouse;
};

counter

sometimes setinterval and getTimer all go wrong

use this to count instead as a global counter. the timing should be multiplied by framerate.

stop();
delete this.onEnterFrame;
var counter = 0;
this.onEnterFrame = function() {
    if (counter == 30) {
        delete this.onEnterFrame;
        play()
    }
    ++counter;
    //trace(counter);
};

total time of banner

function updateTimer():Void {
	timer = getTimer();
	timer = timer/1000;
}

var intervalID:Number = setInterval(updateTimer, 100);

and

// on last frame
stop();
trace("Total Time = "+timer+" seconds");

set kerning letterspacing of dynamic text field

var my_fmt:TextFormat = new TextFormat();
my_fmt.letterSpacing = 5;

// set the text format

time_txt.setTextFormat(my_fmt)
time_txt.setNewTextFormat(my_fmt)

random frame

_root.gotoAndPlay(random(5));

gotoAndPlay(50+random(8));
abc = 50+random(8);
trace(abc);

wait function

function wait(mc, n) {
	mc.stop();
	//trace("waiting "+mc+" in progress "+n+" secs");
	var myInterval = setInterval(function () {
	mc.play();
	clearInterval(myInterval);
	}, n*1000);// stop for n seconds
}

_root.wait(this,3);

setInterval

function callback() { 
       trace("interval called"); 
}
var intervalID; 
intervalID = setInterval( callback, 1000 ); 

// sometime later 
clearInterval( intervalID );
so every 1000 milliseconds, callback would be called
but then after that u clear Interval
so it wont continue?

scrolling all directions

#include

  1. include "filename.as"

this is pretty damn handy for content population

filter

    import flash.filters.BlurFilter;
    var myBlurFilter = new BlurFilter (10,2,3);

  
comms_2.onRollOver = function() {
bb2.gotoAndPlay("open");
bb1.filters = [myBlurFilter];
bb3.filters = [myBlurFilter];
bb4.filters = [myBlurFilter];

}
comms_2.onRollOut = function() {
bb2.gotoAndPlay("close");
bb1.filters = []; 
bb3.filters = []; 
bb4.filters = []; 
}

quit / close btn

getURL("javascript:window.close()");
fscommand("quit", "true");

setMask

mask.cacheAsBitmap = true; // dont need in cs3
img_mc.cacheAsBitmap = true;
img_mc.setMask("mask");

linebreak for xml

Linebreakxml.png

fscommand for fullscreen


fscommand("fullscreen", true);
fscommand("allowscale", false); // if you have images that cannot be distorted out of dimensions


cssStyle

import TextField.StyleSheet;

newHTMLboxText = "
<h1>SAMPLE HEADER</h1> sample text text text";

var newCSS:StyleSheet = new StyleSheet();
newCSS.setStyle("body", {fontSize:'12',color:'#000066'});
newCSS.setStyle("h1", {fontSize:'45',color:'#000000'});
newCSS.setStyle("a:link", {color:'#0000CC',textDecoration:'none'});
newCSS.setStyle("a:hover", {color:'#0000FF',textDecoration:'none'});
newCSS.setStyle("b", {fontWeight:'bold'});

newHTMLbox.html = true;
newHTMLbox.styleSheet = newCSS;
newHTMLbox.htmlText = newHTMLboxText;

eval vs array

eval and array are NOT THE SAME THING

eval is the old style of saying "eval this argument quick and return it here on the same spot" - it can only be used in first half of argument

unloading XML

it is harder to unload an XML than it is to take the xml-fed file, chuck it into another swf, and loadmovie instead

loadMovie("gallery.swf",_root.containment);

and when you dont want the gallery at all just do this:

unloadMovie("_root.containment");

hurgh



== Loop with eval ==

<pre>	for (var i = 0; i<numberOfBanners; i++) {

		_root.wn.banner_mc.createEmptyMovieClip("ButtonImage"+i, i+20);
		eval("ButtonImage"+i).lineStyle(1,0,40);
		eval("ButtonImage"+i).beginFill(0xFFFFFF,20);
		eval("ButtonImage"+i).lineTo(-5,0);
		eval("ButtonImage"+i).lineTo(-5,20);
		eval("ButtonImage"+i).lineTo(15,20);
		eval("ButtonImage"+i).lineTo(15,0);
		eval("ButtonImage"+i).lineTo(-5,0);
		eval("ButtonImage"+i).endFill();
		eval("ButtonImage"+i)._x = 20+i*24;
		eval("ButtonImage"+i)._y = 10;
		_root.wn.banner_mc.createTextField("ButtonNum"+i, i+10, 0, 3, 20, 20);
   // createTextField("INSTANCE NAME", depth, x, y, width, height);
		eval("ButtonNum"+i).text = i+1;
		var prufont:TextFormat = new TextFormat();
		prufont.size = 13;
		prufont.font = "Arial";
		eval("ButtonNum"+i).setTextFormat(prufont);
		eval("ButtonNum"+i)._x = 20+i*24;
		eval("ButtonNum"+i)._y = 10;
		eval("ButtonImage"+i).onRelease = function(){
			trace("buttonycliksy");
			play();
			}
	}

Skinning Components

http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002480.html

ASO

ASO files exist in an aso subdirectory of the Classes folder within your LocalData directory (as see in your global classpath list by default - not the one in the Flash install directory). What these files are, are "caches" of your class files. Being the slick application Flash is, to improve performance in publishing your movies, it creates temporary pre-compiled versions of your external classes every time you test or publish your movie. Then, the next time you test or publish, it can reuse those pre-compiled aso versions without having to recompile the original .as files (assuming they didn't change) saving time and allowing for a faster publish.

Adobe says : If you experience problems in which Flash appears to be compiling older versions of a file you have edited, delete the ASO files and then recompile. If you plan to delete ASO files, delete them when Flash is not performing other operations, such as checking syntax or exporting SWFs.

multiple flash overlay / flashblock glitch

extremely strange multiplication of gradient shadow (w/ transparency) over html area between the overlap of two flash overlays.

SOLUTION: INCREASE AREA OF WHITE BACKGROUND ON LOWER FLASH FILE SO NO GAP

visibility

	personal_dd._visible = false;
	business_dd._visible = false;
	aboutus_dd._visible = false;
	mediacentre_dd._visible = false;

personal.onRollOver = function() {
	personal_dd._visible = true;	
	business_dd._visible = false;
	aboutus_dd._visible = false;
	mediacentre_dd._visible = false;
}

SOLUTION FOR DROPDOWN MENUS

ACTUALLY THERE"S ALSO _enabled which is better

use discretion i suppose

level0 vs root

http://forum.oxylusflash.com/sliding-list/324-scroll-when-loaded-into-parent-swf.html

http://kb2.adobe.com/cps/146/tn_14686.html

When a SWF file is loaded into the Flash player, it's main timeline is loaded into level 0. In this movie and this movie only will _root and _level0 reference the same timeline. Additional SWF files can be loaded into additional levels using loadMovie or loadMovieNum. References of _root in those files then reference the level in which that SWF referencing _root was loaded. For example, if a SWF is loaded into level 2, a reference to _root in that SWF will reference the same timeline that _level2 references, but will not reference the same timeline as _level0. A reference to _root will only equal _level0 in the SWF that was first loaded into the player (level 0).

If you are using loadMovie to load SWF files into movie clips instead of levels, _root in those movie clips will still reference the main timeline of the level, not the main timeline of the SWF that was loaded into the player. If you want _root to reference the main timeline of that SWF, you will want to use _lockroot.

onRelease vs onMouseDown

onMouseDown doesn't matter what the mc is. the whole file is a fucking button. use onRelease for MCs............

ALIGNMENT IS QUITE IMPORTANT

SO USE THE DAMN ALIGN PANEL MORE think about registration points and dont just move them all.....

audio button

stopAllSounds();

because all my sounds were on the stage as events the global volume is the only way to do it

// changes colour of audio button and controls global volume....

var globalVolume:Sound = new Sound();
var audioState = 1;

Color.prototype.clearRGB = function(){
     audiospecial.setTransform({ra:100, rb:0,ga:100,gb:0,ba:100,bb:0,aa:100,ab:0});
}

audiospecial.onRollOver = function() {
	var newColor = new Color(eval(audiospecial));
	newColor.setRGB(0xFFFFFF);
};

audiospecial.onRollOut = function() {
	var newColor = new Color(eval(audiospecial));
	newColor.setRGB(0xFE6AFF);
};

audiospecial.onMouseDown = function() {
if (audioState == 1){
audiospecial.gotoAndPlay("soundoff");
globalVolume.setVolume(0);
audioState = 0;
} else if (audioState == 0) {
audiospecial.gotoAndPlay(1);
globalVolume.setVolume(100);
audioState = 1;
}
else{
	null
}
};

failproof mouseover

on the main timeline

stop();
mc1.onRollOver = function() {
	mc1.gotoAndPlay("open");
};
mc1.onRollOut = function() {
	mc1.gotoAndPlay("close");
};

on mc1 -

  • put a stop on frame 1
  • frame 2 name it as open
  • frame 10 (or whatever) name it as close

swapdepths

mc.swapDepths("1000");

or each time you can up the depth using variable

on (press, release, dragOver, dragOut) {
_root.x +=5;
mc.swapDepths(_root.x);
}

loadmovie

loadMovie("somecontent.jpg/gif/swf/png", "_root.container");

ACTIONSCRIPT 2.0

BOOLEAN

    var rollOverFish:Boolean = false

    fish.onRollOver = function() {
       if (rollOverFish == false) {
          //Some Action
          rollOverFish = true;
       } else {
          null;
       }
    }

OTHERS

#include "filename.as"          // includes the .as file at runtime (must be in same folder as .fla)


        /*  CONDITIONALS  */

var message = "yellow";                         // the equal sign assigns values to variables
trace ("big " + message + " truck");            // prints "big yellow truck"
if (message == "yellow") {                      // the double equal sign checks to see if variables are equal
trace ("yes, i did say big yellow truck.");     // prints "yes, i did say big yellow truck"
trace (typeof message);                         // prints "string"
var x = a;                                      // prints "number"
trace (typeof a)
}

var x = 1;
while (x <= 5) {                // as long as x is less than 5...
trace (x);                      // return 1 in output
x = x + 1;                      // return 2 3 4 5 in output
}


        /* BUTTONS IN A QUIZ */

button1.onRelease = function () {         // on pressing button 1
this._parent.q1answer = 1;                // assigning 1 to q1 answer
this._parent.gotoAndStop("q2")            // after which we go to frame labelled as q2
}
if (q1answer == 3) {                      //  if answer was right
  totalCorrect = totalCorrect++;          //  increase number of total correct qns by one
}                                         //    you could even do something like
                                          //    if ( 3 < 300 ) { do something }
                                          //    if ( "a" < "z" ) { do something }
                                          //
     

        /* FUNCTIONS IN DIFFERENT LAYERS/SCENES */

function T1over() {                             // this code is placed on main stage
        _root.one_mc.gotoAndStop(2);            // but refers to a one_mc on the stage
        getURL('javascript:modifyT1();');
}

_root.one_mc.onRollOver = T1over;               // this would be same

on (rollOver) {                                 // this placed on one_mc
        gotoAndStop(2);                         // is the same as above
        getURL('javascript:modifyT1();');       // OPTIONALLY use frame labels instead of frame no.
}

        /*  ROTATION  */
        
on (rollOver) {
        this._rotation = + 45;          // Values from 0 to 180 represent clockwise rotation;
}                                       // values from 0 to -180 represent counterclockwise rotation


        /* LOADING IMAGES IN */
        
this.createEmptyMovieClip("image_mc", 1);       // to create a dynamically created mc
image_mc.loadMovie("giraffe.jpg");              // mc loads an image

image_mc.removeMovieClip();                     // to remove the dynamically created mc


        /* CREATING TEXT FIELDS */
        
var score = 99;
this.createTextField("score_txt", 1, 150, 200, 200, 20);
score_txt.text = "  "+score+" points";  // prints 99 points in score_txt field
score_txt.textColor = 0xFF0000;                        // text color is red

                                // myMovieClip.createTextField (instanceName,depth,x,y,width,height)
                                //        instanceName  A string that identifies the instance name of the new text field.
                                //        x An integer that specifies the x coordinate of the new text field.
                                //        y An integer that specifies the y coordinate of the new text field.
                                
myFormat.underline  = true;
myFormat.Color = 0xFF0000;                  // alternatively, score_txt.textColor also works
myFormat.bold = true;
myFormat.size = 16;
myFormat.font = "Georgia";                  // if you choose to set a font, make sure you include dummy field offstage
                                            // which uses your font, has font embedding turned on (character)
                                            // and if you use bold/italic/regular variation you must include each type
                                            
score_txt.setTextFormat(myFormat);          // applies format to all of score_txt
score_txt.setTextFormat(12, 27, myFormat);  // applies format to only the 12-27th character in score_txt. HARDCORE....


this.createTextField("more_txt", 1, 180, 250, 200, 20);
more_txt.html = true;                                           // creating a dynamic (highlightable) txtfield
more_txt.htmlText = "look its a
<font color='#00ccff'><u>                                       // you will have to format it all in html
<a href='http://www.sg'>link</a>
</u></font>";

        /* LEARNING HOW TO DRAW */

_root.lineStyle(1, 0x000000, 50);                        // line-thickness, colour, opacity
_root.moveTo(50, 100);                                                // cross hatch drawing
_root.lineTo(200, 100);                                                // first number is the horizontal value
_root.moveTo(50, 150);                                                // second number is the vertical value
_root.lineTo(200, 150);
_root.moveTo(150, 50);
_root.lineTo(150, 200);
_root.moveTo(100, 50);
_root.lineTo(100, 200);

_root.lineStyle(5, 0x000000, 20);                        // drawing a square
_root.moveTo(50, 50);
_root.lineTo(200, 50);
_root.lineTo(200, 200);
_root.lineTo(50, 200);
_root.lineTo(50, 50);

_root.lineStyle(10, 0x000000, 100);           // drawing a deformed circley thing with a fill.
                                              // note: to have no border, omit linestyle
_root.moveTo(125, 50);                        // move starting point from 0,0 to elsewhere
_root.beginFill(0x888888, 50);                // add a fill of 50% opacity. can
_root.curveTo(200,50, 200,125);               // _root.curveTo(controlX, controlY, anchorX, anchorY);
_root.curveTo(200,200, 125,200);
_root.curveTo(50,200, 50,125);
_root.curveTo(50,50, 125,50);
_root.endFill


        /* drawing program */

_root.createEmptyMovieClip("line",1);

_root.onMouseDown = function() {
line.moveTo(_xmouse,_ymouse);
line.lineStyle(1,0x000000,100);

this.onMouseMove = function() {
line.lineTo(_xmouse,_ymouse);
updateAfterEvent();
}
}


        /* Loading external swfs */

stop();                                         // place this on the frame where you want to stop 
container_mc.loadMovie('filename.swf');         // create blank container_mc at 0,0


          /* DRAWING A GRID WITH AS  */

stop();
var cols:Number = 50;
var rows:Number = 50;
var w:Number = stage.stageWidth/cols;
var h:Number = stage.stageHeight/rows;
var points:Array = Points.createPoints(rows, cols, w, h);

//drawing rows
for (var i:Number=0; i<rows+1; i++) {
	graphics.lineStyle(1, 0xEEEEEE);
	graphics.moveTo(0, points[i*(cols-1)].y-1);
	graphics.lineTo(points[cols-1].x+w, points[i*(cols-1)].y-1);
}

// drawing cols
for (var j:Number=0; j<cols; j++) {
	graphics.lineStyle(1, 0xEEEEEE);
	graphics.moveTo(points[j].x-1, 0);
	graphics.lineTo(points[j].x-1, points[points.length-1].y+h);
}


ACTIONSCRIPT 3.0

actionscript object-oriented programming (OOP)

  • Structure: main class (starts the program) > classes (blueprint which describes characteristic and behaviour of the object) > objects (interoperating instances of classes in the program)
  • store your flas and swfs in one directory (eg: /hulkdash/ )
  • store the actionscript source files in /hulkdash/src/
  • main class code should be in the file hulkdash.as (filename matches class name)
  • use packages


actionscript, that infuriatingly intractable marshmellow fluff... so far i have only understood the most basic of concepts, but now i will try to learn it well.


alpha

// set movie clip's alpha (transparency) to 50% immediately
myMC._alpha = 50%

// set up alphacounter, if alphacounter is undefined then it sets it to 99. otherwise alphacounter is to decrease to 0 and delete itself.
myMC.onEnterFrame = function (){
this.alphaCount = (this.alphaCount == undefined) ? 99 : --this.alphaCount;
this._alpha = this.alphaCount;
	if (this._alpha <= 0) {
	delete this.onEnterFrame;
	}
}

// change it to ++ to make it go up

Codehinting

to keep with good practice you should keep to these common suffixes so that any programmer can read your code easily without finding it utterly incomprehensible.

variables:

  • must start with letters, underscore or dollarsign.
  • no hyphens or other punctuation besides the underscore.
  • cannot start with a number.
  • are case-insensitive, but keep it constant or you might get confused
  • xxx_str // means the variable contains a string
  • xxx_arr // means the variable contains an array

Conditionals

var message = "yellow";
trace ("big " + message + " truck");                // prints "big yellow truck"
if (message == "yellow") {
trace ("yes, i did say big yellow truck.");        // prints "yes, i did say big yellow truck"
}
= assigning value
== comparing values

loops

this sequence...
trace (101);
trace (102);
trace (103);
trace (104);
trace (105);
is equal to:
var x = 101;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);
is also equal to:
var x = 101;
while (x <= 105) {     // as long as x is less than 105...
trace (x);
x = x + 1;           // ...continue to trace x but add one each time
}
they all print:
101
102
103
104
105

functions

sample:

function area(height, width){
return height * width;
}
area1 = area(10,15);
area2 = area(10,20);
area3 = area(10,20);

event based execution

someObject.onSomeEvent = someFunction;

for example:

skaGirl.onRelease = dirtyskanking;            // the object named skaGirl will dirtyskank when mouse is released

function dirtyskanking () {
this._parent._rotation = 360;                     // defines the rotation of the dirtyskanking.
}

sample

quiz

button1.onRelease = function () {         // on pressing button 1
this._parent.q1answer = 1;                // assigning 1 to q1 answer
this._parent.gotoAndStop("q2")            // after which we go to frame labelled as q2
}

if (q1answer == 3) {                      //  if answer was right
  totalCorrect = totalCorrect++;          //  increase number of total correct qns by one
}

confused about root, this, and parent? so am i!

this piece of code would work ON a frame on the main stage, one_mc being an object onnit.

function T1over() {
	_root.one_mc.gotoAndStop(2);
	getURL('javascript:modifyT1();');
}

_root.one_mc.onRollOver = T1over;

actionscript and javascript

tips

  • use frame labels rather than frame numbers. you could call a starting frame "init".
  • dont use too many functions

See Also