circlecube

RSS comments
LinkedIn Twitter delicious fb last.fm

Archive for the ‘tutorial’ Category

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

Get Adobe Flash player

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 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

  • del.icio.us
  • Digg
  • email
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS

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

1
2
3
4
5
6
on (press) {
    startDrag (this);
}
on (release, releaseOutside) {
    stopDrag ();
}

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!

1
2
3
4
5
6
7
8
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();
}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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();
}

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

Get Adobe Flash player

Source

as3dragdrop-ball.fla

  • del.icio.us
  • Digg
  • email
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS
23 Apr 2009

Flash Drag and Drop Tutorial | startDrag Actionscript

Author: Evan Mullins | Filed under: 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

Get Adobe Flash player

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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();

Source

Download fullscreen_tut.fla file

  • del.icio.us
  • Digg
  • email
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS
23 Mar 2009

How to use fullscreen in AS3 | Stage Display State Tutorial

Author: Evan Mullins | Filed under: tutorial

To view the full fullscreen tutorial go here: How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_keyboard_bug_thumbnail
Sucks when you seem to have a bug in your code somewhere so you dissect your code over and over and are convinced that according to your code, everything should be fine, so you come back later thinking fresher eyes will see it, and still can’t find the cause, and then resort to debugging with various trace statements…

I’ve been developing a custom flash player in as3. Fullscreen and all those bells and whistles… I could test locally and eveything was beautiful… but then upload and test in the browser and when I would go into fullscreen mode, the video would pause. Pretty annoying bug! So I’d go through my code and examine anywhere a call to pause the video (there are only two): pressing the play/pause button and pressing the spacebar (keyboard shortcut). I couldn’t find any correalation. I was thinking adobe must be doing some crazy security things when going into fullscreen… but no, no other video player I’ve seen does this!
After commenting out my keyboard events, the bug is fixed! But I still can’t use the spacebar to pause/play. I love this functionality for usability. Isn’t that pretty standard for video? space to pause, it’s like second nature to me.

Does entering fullscreen really trigger a keyboard event equivalent to pressing my spacebar!? Sure enough. how much sense does that make, but it gets better! I had a friend test this swf and it worked fine for him. No pause on fullscreen! Wha!? Using good ole IE7… So yes, it’s a browser specific actionscript bug, firefox even! That was one of the things I liked about flash initially, not too much to mess with as far as cross browser issues once you get the swf embedded in the html, or so I thought.

So after playing with booleans to try to control when the keyboard events will be working.

Has anyone experienced this or another issue that just left you baffled, even after you figured out the bug?!

Well, I’ve done the right thing, I’ve posted about it to hopefully help anyone else having this issue. I created a test case file to rule out anything else in my code and make sure I’m not crazy.

Get Adobe Flash player

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

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

function fullscreenToggle(e:MouseEvent = null):void {
    //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;
    }
    onFullscreenChange();
}
function onFullscreenChange(e:FullScreenEvent = null):void {
    if (stage.displayState == StageDisplayState.FULL_SCREEN) {
        tracer("full screen");
        fsb.visible = false;
        ssb.visible = true;
    }
    else {
        tracer("small screen");
        fsb.visible = true;
        ssb.visible = false;
    }
    tracer("toggle to "+stage.displayState);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);

function keyDownListener(e:KeyboardEvent) {
    tracer("keyboard: keyCode: "+ e.keyCode.toString());
}
var tracerwindow:TextField;
function tracer( ...args){
        if (tracerwindow == null){
            tracerwindow = new TextField();
            tracerwindow.width = stage.stageWidth/2;
            tracerwindow.height = stage.stageHeight;
            tracerwindow.multiline = true;
            addChild(tracerwindow);
        }
       
        for (var i:uint = 0; i < args.length; i++) {
            tracerwindow.appendText(args[i].toString() + " ");
        }
        tracerwindow.appendText("\n");
        trace(args);
}

other places that I’ve found this mentioned that helped me understand what was going on:

http://dreamweaverforum.info/actionscript-3/123202-keyboard-event-full-screen.html

http://bugs.adobe.com/jira/browse/FP-814

  • del.icio.us
  • Digg
  • email
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS

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. :)

Get Adobe Flash player

Actionscript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//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<numBalls; ballNum++){
        var c1:Number = randomColor();
        var c2:Number = randomColor();
       
        //create ball
        var thisBall:MovieClip = new MovieClip();
        thisBall.graphics.beginFill(c1, .9);
        thisBall.graphics.lineStyle(defaultBallSize/3, c2, .9);
        thisBall.graphics.drawCircle(defaultBallSize, defaultBallSize, defaultBallSize);
        thisBall.graphics.endFill();
       
        addChild(thisBall);
       
        //coordinates
        thisBall.x = Math.random() * stage.stageWidth;
        thisBall.y = Math.random() * stage.stageHeight;
        //percieved depth
        thisBall.ballNum = ballNum;
        thisBall.depth = ballNum/numBalls;
        thisBall.scaleY = thisBall.scaleX = thisBall.alpha = ballNum/numBalls;
        //velocity
        thisBall.vx = 0;
        thisBall.vy = 0;
        thisBall.vz = 0;
       
        //ball animation
        thisBall.addEventListener(Event.ENTER_FRAME, animateBall);
    }
}

var dampen:Number = 0.95;
var maxScale:Number = 1.3;
var minScale:Number = .3;
var maxAlpha:Number = 1.3;
var minAlpha:Number = .3;
function animateBall(e:Event):void{
    var thisBall:Object = e.target;
    //apply randomness to velocity
    thisBall.vx += Math.random() * 0.2 - 0.1;
    thisBall.vy += Math.random() * 0.2 - 0.1;
    thisBall.vz += Math.random() * 0.002 - 0.001;
   
    thisBall.x += thisBall.vx;
    thisBall.y += thisBall.vy;
    thisBall.scaleX = thisBall.scaleY += thisBall.vz;
    thisBall.alpha += thisBall.vz;
    thisBall.vx *= dampen;
    thisBall.vy *= dampen;
    thisBall.vz *= dampen;
   
    if(thisBall.x > 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);
}

Source:

as3random_brownian_movement.fla

  • del.icio.us
  • Digg
  • email
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS
10 Feb 2009

Random Movement | Brownian revisited for as3

Author: Evan Mullins | Filed under: tutorial