Flashvars and as3

flashvars_as3_thumbFlashvars and actionscript 3! Flashvar is a way that in your html embed codes (object tags) you can send variables and values into your swf file. These variables can then be grabbed internally and used your programming! Examples of these could be images that you want to use in your swf but don’t want to import or hardcode them into the flash file or paths to xml or flv files to use as well. Actionscript 3 has a different procedure than as2 did as to how you read these flashvars from the actionscript side. The embed codes and html side of things are still the same, but in case your new to actionscript altogether, I’ll give an example of the html as well. [cc lang=”html”] [/cc] In actionscript 3 we use the loaderInfo object to access the flashvars. The parameters Object of the loaderInfo will contain all the flashvar variables and values. [cc lang=”actionscript”] this.loaderInfo.parameters [/cc] As an example of something that is visual I’ve created this little app to read some options from flashvars about colors. An app that will read a list of colors and update a box that is on the stage already to those colors with the specified delay. I always have fun with randomness so I threw in the option for random colors as well. This file looks for certain flashvars: color, loop, delay and random. These are the keys or names of the variables and they are followed by the values you want them to hold. Note that flashvars can be set in any order, so you don’t have to start with color and end with random. In this example I’m looking for 4 flashvars specifically (in any order):

  • colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000 in flash) (default is random)
  • loop:Boolean – whether or not to repeat these colors (default is true)
  • delay:Number – the delay between colors (in seconds). (default is 1 second)
  • random:Boolean – determines whether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false)

This is much more than is required for this example, but I was having fun playing with random colors and timing and options. I figured it doesn’t hurt to show the effect you can have with a couple different variables on one file. Here is an example using the object tags above: [kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/12/flashvars_as3.swf” width=”200″ height=”200″ targetclass=”flashmovie” fvars=”colors=0xFF0000,0x0FF000,0x00FF00,0x000FF0,0X0000FF,0xF0000F&delay=.66&loop=true&random=false”] Get Adobe Flash player [/kml_flashembed] And here are some more (please don’t have a seizure!) Here’s the full source if you’re interested: [cc lang=”actionscript”] /* circlecube.com App to demonstrate the process of getting flashvars from embed code to actionscript (as3) Displays colors specified. looking for 4 flashvars specifically (in any order): colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000) (default is random) loop:Boolean – wether or not to repeat these colors (default is true) delay:Number – the delay between colors (in seconds). (default is 1 second) random:Boolean – determines wether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false) */ //initialize vars var myflashvars:Object = new Object() var myColors:Array = new Array(“random”); var myLoop:Boolean = true; var myDelay:Number = 1; var randomOrder:Boolean = false; var allRandom:Boolean = false; //read flashvars in actionscript3 //if colors flashvars doesn’t exist use these defaults if (!this.loaderInfo.parameters.colors){ myflashvars = {colors: “random”, delay: 1}; } else{ myflashvars = this.loaderInfo.parameters; } //assign flashvars to variables within flash for (var item:String in myflashvars) { trace(item + “:\t” + myflashvars[item]); if (item == “colors”){ myColors = myflashvars[item].split(‘,’); } else if(item == “loop”){ myLoop = parseBoolean(myflashvars[item]); } else if(item == “delay”){ myDelay = myflashvars[item]; } else if(item == “random”){ randomOrder = parseBoolean(myflashvars[item]); } } //use my variables! if (myColors[0] == “random”){ allRandom = true; } var counter:Timer = new Timer(myDelay * 1000); counter.addEventListener(TimerEvent.TIMER, nextColor); trace (“color number: 0”, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); counter.start(); stop(); function nextColor(e:Event):void{ //cycle through colors if (!allRandom && !randomOrder){ if (counter.currentCount+2 > myColors.length){ if (myLoop == true || myLoop == “true”){ counter.reset(); counter.start(); } else{ counter.stop(); } } trace (“color number: “+counter.currentCount, “color hex: “+myColors[counter.currentCount]); setColor(myBox, myColors[counter.currentCount – 1]); } //randomly select a color from the myColors array else if (!allRandom && randomOrder){ var randomColor = Math.floor(Math.random() * myColors.length); trace (“random number: “+randomColor, “color hex: “+myColors[randomColor]); setColor(myBox, myColors[randomColor]); } //randomly create colors else{ trace (“number: “+counter.currentCount, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); } } function setColor(item:DisplayObject, col):void{ if (col == “random”){ setRandomColor(item); } else{ setHexColor(item, col); } } function setHexColor(item:DisplayObject, col:Number):void { var myColor:ColorTransform = item.transform.colorTransform; //check color bounds if (col > 16777215) col = 16777215; else if (col < 0) col = 0; myColor.color = col; item.transform.colorTransform = myColor; } function setRandomColor(item:DisplayObject):void{ setColor(item, (Math.floor(Math.random() * 16777215))); } function parseBoolean(str:String):Boolean { switch(str.toLowerCase()) { // Check for true values case “1”: case “true”: case “yes”: return true; // Check for false values case “0”: case “false”: case “no”: return false; // If all else fails cast string default: return Boolean(str); } } [/cc]

Tutorial to Create a Responsive Image Scroller in ActionScript 3.0

responsive-images-scroller-as3-thumb

I’ve written a tutorial which is published over at flash.tutsplus. This tutorial demonstrates how to create a horizontally scrolling image viewer and covers xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

So check out the Tutorial to Create a Responsive Image Scroller in ActionScript 3.0 over at flash.tutsplus.com!

sourcedemomilestone

You’ll find full source code available for download as well as the demo files and step by step milestones all throughout the tutorial.

Stomper999

Interactive Design project for StomperNet’s tease of the announced reveal on 09/09/09 at 09:09:09!

“Online Marketing Changes Forever!”

stomper999-black
Wanted it to be unexpected, and I think we hit it! Check it out live at stomper999.com!
stomper999-white

Details:
For this project I used flash, html, css and javascript. Tweener for the fading effects. Found a nice stock flash from activeden for the countdown and used jquery and the easing and color plugins.

Forthcoming Actionscript Image Scroller Tutorial

image-scroller-thumbnail

Here is a preview of a file I’m writing a tutorial for. It’s nothing groundbreaking, but it deals with many normal tasks and will show my process a bit. This tutorial will show how to create a horizontally scrolling image viewer. It will cover xml loading & parsing, loading & resizing external images to fit into a scrollable container, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Let me know what you think, and if there’s anything you want specifically mentioned/explained in it I’ll do my best! Or if you have any ideas of how this could be improved.

Update: The article/tutorial has now been published follow the link to theTutorial to Create a Responsive Image Scroller in ActionScript 3.0

Actionscript Drag & Drop Tutorial | Vertical and Horizontal Flash Sliders

as3dragdrop-slider png A specific use of drag and drop which is a bit more complicated than your average drag & drop needs is a slider. You can use components, but I usually prefer using my own graphics and code, partly because the components tend to bloat the filesize of the swf and partly because that’s just how I am, I like to make it myself. Many projects I’ve worked on require sliders as a form of user input, such as a volume control in my video player, or the inputs for my Voter’s Aide app that let users assign value to issues in the 2008 presidential election. I figured I’d just pull out the code I used with the sliders there, since it was already done. The issue with sliders is we need to restrict the dragging to a certain area, which in itself is a line of code, but I also prefer to allow users to click the actual bar as well for quick selection.

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/05/as3dragdrop-sliders.swf” targetclass=”flashmovie” useexpressinstall=”true” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Vertical Slider Steps

The vertical slider here goes from 0 – 100. We need to drag the handle but have it restricted to the slider, so users won’t be confused when they click and drag the handle off the slider and break it. We want to click the background bar of the slider and have the handle snap to that place, and we need to be able to see what value the slider holds (0 – 100). I made this code to be pretty reusable, as long as the slider is set up in similar fashion.

  1. Make graphics for slider bg and handle
  2. Put the graphics into a slider mc
  3. Place them each at 0,0 and center their registration points (for easier control and code later)
  4. Assign button mode to handle and bar (for better usability)
  5. Add Mouse Down Event Listener for handle and bar and assign press function
  6. In bar press function set position of handle according to mouse position, and then call the handle press function
  7. In handle press function remove the Mouse Down listeners and add stage mouse event listeners for both mouse Up and Move (Stage listeners emulate onReleaseOutside (from as2) and also provide more accurate results)
  8. Define dragging area as a rectangle(x, y, width, height), if you’ve do the set up earlier it should be close to Rectangle(0,0,0,slider.bar.height);
  9. Begin dragging handle and apply the drag area limiting rectangle
  10. Mouse Move function find value (should simply be the handle’s y position) and updateAfterEvent for smooth animation
  11. Mouse Release function remove stage listeners, re-add the listeners to the slider and stop dragging

Actionscript (as3)


// Vertical Slider
sliderVertical.handle.buttonMode = true;
sliderVertical.bar.buttonMode = true;
sliderVertical.handle.addEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);
sliderVertical.bar.addEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);

function verticalBarPress(e:MouseEvent):void{
sliderVertical.handle.y = sliderVertical.mouseY;
verticalHandlePress(e);
}
function verticalHandlePress(e:MouseEvent):void {
sliderVertical.handle.removeEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);
sliderVertical.bar.removeEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);
stage.addEventListener(MouseEvent.MOUSE_UP, verticalHandleRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, verticalHandleDrag);
//limit dragging area
var verticalDragArea:Rectangle = new Rectangle(0, 0, 0, -sliderVertical.bar.height+1);
sliderVertical.handle.startDrag(false, verticalDragArea);
}
function verticalHandleRelease(e:MouseEvent):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, verticalHandleRelease);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, verticalHandleDrag);
sliderVertical.bar.addEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);
sliderVertical.handle.addEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);

sliderVertical.handle.stopDrag();
updateVNumber();
}
function verticalHandleDrag(e:MouseEvent):void{
e.updateAfterEvent();
updateVNumber();
}
function updateVNumber():void{
sliderVertical.sliderValue = sliderVertical.stat.htmlText = Math.abs(sliderVertical.handle.y);
sliderVertical.stat.y = sliderVertical.handle.y - sliderVertical.handle.height/2;
}

Horizontal Slider Steps

Pretty much the same as the vertical slider, but adjust heights and y positions to widths and x positions. Note in this example I have a range of (-100 to 100) and to accomplish the bar I just reused the same on flipping it around, so here we have the handle, the barLeft and the barRight. I use both of these combined to calculate the limiting rectangle area.

Actionscript (as3)


// Horizontal Slider
sliderHorizontal.handle.buttonMode = true;
sliderHorizontal.barLeft.buttonMode = true;
sliderHorizontal.barRight.buttonMode = true;
sliderHorizontal.handle.addEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);

function horizontalBarPress(e:MouseEvent):void{
sliderHorizontal.handle.x = sliderHorizontal.mouseX;
horizontalHandlePress(e);
}
function horizontalHandlePress(e:MouseEvent):void {
sliderHorizontal.handle.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
stage.addEventListener(MouseEvent.MOUSE_UP, horizontalHandleRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, horizontalHandleDrag);
//limit dragging area
var dragArea:Rectangle = new Rectangle(-sliderHorizontal.barLeft.width+1, 0, sliderHorizontal.barLeft.width+sliderHorizontal.barRight.width-2, 0);
sliderHorizontal.handle.startDrag(false, dragArea);
}
function horizontalHandleRelease(e:MouseEvent):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, horizontalHandleRelease);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, horizontalHandleDrag);
sliderHorizontal.handle.addEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);

sliderHorizontal.handle.stopDrag();
updateHNumber();
}
function horizontalHandleDrag(e:MouseEvent):void{
e.updateAfterEvent();
updateHNumber();
}
function updateHNumber():void{
sliderHorizontal.sliderValue = sliderHorizontal.stat.htmlText = sliderHorizontal.handle.x;
sliderHorizontal.stat.x = sliderHorizontal.handle.x - sliderHorizontal.handle.width;
}

Source

source as3dragdrop-sliders.fla file

Flash Drag and Drop Tutorial | startDrag Actionscript

I find that Drag and Drop is the most intuitive form of user interaction (at least using a mouse). Actionscript has some of this functionality built in, with the interactive functions startDrag and stopDrag, these can help make our coding pretty easy. If you are transitioning from as2, the code was incredibly simple:

Actionscript2

[cc lang=”actionscript”]
on (press) {
startDrag (this);
}
on (release, releaseOutside) {
stopDrag ();
}
[/cc]
On the movie clip action panel you’d just put that script, which is actually pretty readable even if you don’t know code. The releaseOutside is to keep from the clip missing the release event, because sometimes if a user released the mouse button but was not currently over the clip being dragged for whatever reason, it will not stop dragging.

Actionscript 3

drag-drap-as3-ballSome things have changed with as3, other than the actual coding structure, the biggest change for me doing drag and drop in the new actionscript was that the mouse events have changed. There is no more a press or release. They were replaced with, MOUSE_DOWN and MOUSE_UP. There is no more releaseOutside either and this one is a little more complicated to find among the new MouseEvent list.
Leaving it out works, but we still have the same problem. Check out the working example below and try dragging the red ball to the green or yellow one and drop it there. Since the green is above the red in the layer sequence, the mouse is over the green and when the MouseEvent.MOUSE_UP fires, it’s not on the red ball but on the green, so we don’t get to the code that drops the red ball. So the red ball code basically has times when the dragging sticks even after we release the mouse button. Not to mention the dragging is very jumpy!
[cc lang=”actionscript”]
ballRed.addEventListener(MouseEvent.MOUSE_DOWN, dragRed);
ballRed.addEventListener(MouseEvent.MOUSE_UP, dropRed);
function dragRed(e:MouseEvent):void{
ballRed.startDrag();
}
function dropRed(e:MouseEvent):void{
ballRed.stopDrag();
}
[/cc]

Using the Mouse Move event will help us to customize our behavior a bit more. Plus I wanted to get a more abstract level to it, so I could apply the event listeners to any display object and use the event properties to target the right clips. We begin the drag with the Mouse Down, and the create some other eventListeners for the stage that will watch the Mouse Move and Up events. So clicking on the green or yellow ball, fires the grabMe function which sets the me variable (which will hold any object) to the current target of the event, which should always be the object that you click. So we are using the same code for both the green and yellow ball. I’m a big fan of code consolidation and reuse, it takes a little more effort, but the code is much more clean and portable even. Then we add the event listeners for the stage on MOUSE_MOVE and MOUSE_UP. So first, mthe dragMe function, just says to update after event. This makes the animation smoother cause it only updates the display after the event completes it’s process. Then the drop me function is attached to the stage, so anywhere you release the mouse, the object will stop dragging, plus we remove the stage event listeners and add back the listener for the original object (me). Note the buttonMode property as well, this will make the cursor turn to a hand when you hover that object.
[cc lang=”actionscript”]
ballYellow.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
ballYellow.buttonMode = true;
ballGreen.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
ballGreen.buttonMode = true;

var me:Object;
function grabMe(e:MouseEvent):void{
me = e.currentTarget;
me.removeEventListener(MouseEvent.MOUSE_DOWN, grabMe);
me.startDrag();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMe);
stage.addEventListener(MouseEvent.MOUSE_UP, dropMe);
}
function dropMe(e:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMe);
me.stopDrag();
me.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
}
function dragMe(e:MouseEvent):void {
e.updateAfterEvent();
}
[/cc]
This functionality is much smoother and then when I want to add more code to the dragging or dropping, I have a place to do it already!

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/04/as3dragdrop-ball.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Source

as3dragdrop-ball.fla

How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_tut png
One of the best features of the flash player if you’re doing video is the fullscreen functionality. It has been a question I’ve heard repeatedly. There are limits to what you can do in fullscreen. Such as minimal keyboard support while in fullscreen. But it is perfect for a video player! Who doesn’t want to see a video expanded to full screen mode?

There are a couple things to consider when coding fullscreen into your flash. Remember the hard coded “Press Esc to exit full screen mode.” that Adobe has placed into the flash player. This is untouchable by developers, and the function returns to normal stage display state. So we call the function to go fullscreen, but the exit fullscreen has already been written for us. This can pose a problem though, when we need the player to do something when we exit fullscreen, that is when we want it to do something more than the generic black box function adobe includes.

Steps

  1. specify stage properties
  2. full screen button and listeners
  3. stage fullscreenEvent listener
  4. (functions for each)
  5. allowfullscreen = true

Example

[kml_flashembed fversion=”9.0.28″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_tut.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]Get Adobe Flash player

[/kml_flashembed]

1. Stage properties exist that allow us to specify what type of fullscreen we want.  We can have the swf scale to fit the fullscreen area (StageScaleMode.SHOW_ALL), not scale at all (StageScaleMode.NO_SCALE), skew to fit fullscreen (StageScaleMode.EXACT_FIT), and scale to fill fullscreen area (Stage.ScaleMode.NO_BORDER).  We may also edit the alignment of the stage in the fullscreen area; in this example I’m using TOP, but refer to documentation for more options

2. Adobe has placed restrictions on when a swf can enter fullscreen, and has deemed that it must result from a user interaction, a mouse click or keystroke. So create your buttons (or keyListeners). I prefer to have one button to enter fullscreen and another to exit, and have them both call the same function to toggle fullscreen. It gives a clearer communication to the user. I then control the visibility of these buttons depending on the current display state of the stage.

3. Another listener to watch the stage dispaly state. stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange); This will fire every time the stage display state changes. We need this because as I mentioned earlier, when entering fullscreen we use our own function, but the ‘hit esc to exit fullscreen’ functionality is built into the flash player, we can’t update our stage layout or button visibility without watching to catch when the display state is changed. Using this method we can update our stage layout any and every time.

4. Of course flesh out the fullscreenToggle function to include anything else you need.

5. Lastly, for a SWF file embedded in an HTML page, the HTML code to embed Flash Player must include a ‘param’ tag and ’embed’ attribute with the name ‘allowFullScreen’ and value ‘true’, like this:

<object>
    ...
    <param name="allowFullScreen" value="true" />
    <embed ... allowfullscreen="true" />
</object>

The allowFullScreen tag enables full-screen mode in the player. If you do everything else right and don’t include this in your embed codes, fullscreen will not work. The default value is false if this attribute is omitted. Note the viewer must at least have Flash Player version 9,0,28,0 installed to use full-screen mode. Also note that  the simple (ctrl + enter) testing your movie in flash will not allow fullscreen either, you must use the debug tester (ctrl + shift + enter) … or go open the published swf in flash player.

Actionscript

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP;

var stageDisplayAdjustCounter:uint = 0;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);

fsb.buttonMode = true;
ssb.buttonMode = true;

//fullscreen buttons need this to adjust the stage display state.
//pressing escape to exit fullscreen bypasses this function
function fullscreenToggle(e:MouseEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. fullscreenToggle from “+stage.displayState+”\n”);
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
//here we subtract 1 from the counter because it has already incremented (in onFullscreenChange) when we set the display state above

status.appendText((stageDisplayAdjustCounter-1)+”. fullscreenToggle to “+stage.displayState+”\n”);
status.scrollV = status.maxScrollV;

}

//this function is called every and anytime the stage display state is adjusted
//either by pressing our buttons or
function onFullscreenChange(e:FullScreenEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. onFullscreenChange\n”);
status.scrollV = status.maxScrollV;
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
fsb.visible = false;
ssb.visible = true;
}
else {
fsb.visible = true;
ssb.visible = false;
}

stageDisplayAdjustCounter++;
}

onFullscreenChange();

[/cc]

Source

Download fullscreen_tut.fla file

#tweetcoding

If you didn’t know, Grant Skinner has introduced an interesting competition called tweetcoding!

Mixing as3 with the 140 character limit of tweeting he calls for the community to tweet visually interesting source code.

I’ve played a bit with it and tweeted my first #tweetcoding entry! See more tweetcoding here

[cc lang=”actionscript”]
g.clear(),o[++i]={x:mouseX,y:mouseY,c:r()*0xFFFFFF};for each(k in o)k.c*=.9,g.beginFill(k.c),ls(i,k.c),g.drawCircle(k.x,k.y,1),g.endFill();
[/cc]

Want to see my entry? Here it is!

tweetcode_circlecube_a png

Random Movement | Brownian revisited for as3

I have had feedback that certain random movements I program are a bit “jumpy”. Such as my old brownian movement tutorial and I really noticed it in my last tutorial, the parallax 3d depth effect tutorial. I’ve been thinking about it and looking around at some code and now have this updated brownian movement example! Updated for as3 as well as making it less jumpy.

as3brownian thumb pngFirst I’ll explain what I’ve found to be the reason of the jumpiness. And then explain and show what can be done to make this movement be more smooth.

So to examine the old jumpy code. Jump back to the first version post here. I think my technique was well thought out here, but the application was poor. It was recalculating the velocities every single frame and then incrementing the coordinate positions by the newly calculated velocities… This is where the jumpiness comes in. Even though the random value was named velocity, it didn’t actually affect the dot’s velocity, it was just a variable that stored the random value used to move the current x/y coordinates.
To help the animation be more smooth, the velocity needs to be more smooth. The velocity, rather than calculating it fresh each frame, should be randomly modified each frame. And then the new velocity will calculate the new ‘random’ position. Another addition is to introduce another force to dampen the velocity over time, so things don’t get too crazy…

Steps:

  1. Modify velocity randomly
  2. With velocity and current position, calculate a new position
  3. Dampen the velocity

Example:

Here I have a velocity for the x coordinate as well as the y. I’m also experimenting with a z velocity. This adjusts the alpha and scale for depth perception. It doesn’t actually edit the depth or layer the dot shows up on the stage however… keyword here: experimenting. 🙂
[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/02/as3random_brownian_movement.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″ wmode=”transparent”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript:

[cc lang=”actionscript”]
//number of balls
var numBalls:uint = 50;
var defaultBallSize:uint = 30;

//init
makeDots();

function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum stage.stageWidth) {
thisBall.x = 0 – thisBall.width;
}
else if(thisBall.x < 0 - thisBall.width) { thisBall.x = stage.stageWidth; } if(thisBall.y > stage.stageHeight) {
thisBall.y = 0 – thisBall.height;
}
else if(thisBall.y < 0 - thisBall.height) { thisBall.y = stage.stageHeight; }if (thisBall.scaleX > maxScale){
thisBall.scaleX = thisBall.scaleY = maxScale;
}
else if (thisBall.scaleX < minScale){ thisBall.scaleX = thisBall.scaleY = minScale; } if (thisBall.alpha > maxAlpha){
thisBall.alpha = maxAlpha;
}
else if (thisBall.alpha < minAlpha){ thisBall.alpha = minAlpha; } }function randomColor():Number{ return Math.floor(Math.random() * 16777215); } [/cc]

Source:

as3random_brownian_movement.fla

Dynamic 3d space | Floating Sketches Tutorial

parallax_thumbI’ve had quite a few questions about how to make depth in flash. Earlier (like, 2 years ago) I put up an experiment file to give some interactive depth to some sketchbook sketches, see Floating Sketches. I’ve finally gotten around to translating that into as3. It’s still the same basic idea, Create layers of levels, and have each one respond to the mouse a little differently. The ‘closer’ depths will move faster while the farther away depths will be slower. A simple technique called Parallax.

  1. Seperate the scene into layers
  2. Place the layers in the correct depth
  3. Make closer layers react fast and farther layers slower

Example

[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/01/depth.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″]

Get Adobe Flash player

parallax_thumb
[/kml_flashembed]

Actionscript

[cc lang=”actionscript”]
//define number of layer.
var numLayers:uint = 15;
//number of items in a layer
var numBallsPerLayer:uint = 100;
var defaultBallSize:uint = 25;

var stageWidth3d:uint = 800;
var stageHeight3d:uint = 800;

var layers:Array = new Array();
//init
makeMatrix();
//3d created by layers and placing objects on each layer – the layer has it’s own distance, simulated by movement and alpha

function makeMatrix():void {
//walk through desired number of layers
for (var layerNum:uint=0; layerNumSource

depth.fla