Home Contact RSS

Brownian Movement in Actionscript | Random Motion Tutorial

Overview

Having things drift around or move randomly has always interested me. Having an animation that is never going to be the exact same thing is very exciting. The focus turns from key-ing exact animations to programming a feel and letting the animations take car of themselves! One type of seemingly random motion is Brownian motion. This gives the movement a random walk wandering look, it will just drift around with no real direction.

Steps

Step by step this process is very simple. In every random motion you create the random number, and apply it to the property. If you want constant random action (motion) rather than just random placement, you repeat that over and over.

  1. Make a random number (random velocity)
  2. Apply the random number (apply velocity to property)
  3. Repeat (if needed)

To create a random number in actionscript, use Math.random(), which creates a random number between 0 and 1. Usually you’ll want to scale it to a range you want to use. If you want a number between 50 and 100, you’d do Math.random() * 50 + 50. *50 to scale it to 0-50, and + 50 to bring it up to 50 - 100. Also if we want to get a 100 range around 0 (-50 - 50) we would do Math.random() * 100 - 50. In the code below I’ve abstracted this to Math.random() * this.randomRange - this.randomRange/2.

Example

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)
Here I’ve got dots created and placed randomly, with randomly set scale and alpha. On every frame each dot has a random velocity applied to it’s x and y coordinates.
The yellow dot is the simple example (code below) and the rest are included in the complex example below.

Actionscript

Simple Example:

  1. dotOne.onEnterFrame = function() {
  2. //create a random velocity for x and y direction
  3. vx = Math.random() * 4 - 2;
  4. vy = Math.random() * 4 - 2;
  5. //apply velocity to coordinates
  6. this._x += vx;
  7. this._y += vy;
  8. }

Complex example:

  1. var numDots = 25;
  2. var randomRange = 1;
  3.  
  4. for(var i=1; i<=numDots; i++) {
  5. //create a new dot
  6. duplicateMovieClip(_root.dot, "dot"+i, i);
  7. //save it's ref path for use
  8. theDot = _root["dot"+i];
  9. //give it random coordinates
  10. theDot._y = Math.random() * Stage.height;
  11. theDot._x = Math.random() * Stage.width;
  12. //give each dot a distinct random range
  13. theDot.randomRange = i/numDots;
  14. //give each dot a random size and transparency
  15. theDot._xscale =
  16. theDot._yscale =
  17. theDot._alpha =  i*4;
  18.  
  19. //apply this code on the dot every frame
  20. theDot.onEnterFrame = function() {
  21. //create a random velocity for x and y direction within the specifically created random range for each dot
  22. vx = Math.random() * this.randomRange - this.randomRange/2;
  23. vy = Math.random() * this.randomRange - this.randomRange/2;
  24. //apply velocity to coordinates
  25. this._x += vx;
  26. this._y += vy;
  27. }
  28. }

Download

randomMotion.fla

Tags: , , , , , , , ,

Shared Object - utilizing the Flash cookie

Overview

The Shared Object is like a cookie for flash. It lets flash store some data on the local machine, so between sessions it can remember things. Learn more from wikipedia.
Shared Objects are used to store data on the client machine in much the same way that data is stored in a cookie created through a web browser. The data can only be read by movies originating from the same domain that created the Shared Object. This is the only way Macromedia Flash Player can write data to a user’s machine. Shared Objects can not remember a user’s e-mail address or other personal information unless they willingly provide such information.

I’ve seen many Local Shared Object tutorials and examples, which have users input their name and/or hometown and other filler data. But I wanted to show how to creatively incorporate shared objects into interactions. So I’ve thrown in many simultaneous examples including the uber-simple ‘input your name and I’ll remember it’ approach. I hope I didn’t throw in so much that it got confusing… just let me know if you have any questions or anything is unclear. Keeping it simply and broad there’s only a few things to know about Shared Objects.

Steps

    Simply put there are only a couple things to worry about with Local Shared Objects

  • Create them.
    • As in create the shared object
  • Write them.
    • As is write to the shared object
  • Set them.
    • As in setting variables in the shared object
  • Get them.
    • As in getting variables back out of the shared object
  • Clear them.
    • As in clearing the shared objec

Actionscript

here’s samples on how to do each of those

  1. /* Create them. */
  2. //make Local Shared Object named myLocalSO(in as) called "myflashcookie" on disk
  3. var myLocalSO:SharedObject = SharedObject.getLocal("myflashcookie");
  4.  
  5. /* Write them. */
  6. //flush the SO, write the SO to disk
  7. myLocalSO.flush();
  8.  
  9. /* Set them. */
  10. //set key's value to specified value in SO
  11. //key is the name of the data
  12. //val is key's value
  13. function setVal(key, val) {
  14. myLocalSO.data[key] = val;
  15. trace(key +" set to "+val);
  16. /* including writing to Shared Object in the setter function */
  17. //flush the SO, write the SO to disk
  18. myLocalSO.flush();
  19. }
  20. /* Get them. */
  21. //get key's value from SO
  22. function getVal(key) {
  23. return myLocalSO.data[key];
  24. trace(myLocalSO.data[key] +" received from "+key);
  25. }
  26. /* Clear them. */
  27. myLocalSO.clear();

Example

here’s my colorful example.
The purple/yellow circle is draggable, so place it where you want it. Enter your name and age in the input boxes. Press the center red ‘Set cookie’ button to copy those values to the shared object that is on your computer now. The red transparent circle represents the cookie positions. You can position the purple/yellow circle from the cookie contents with the dark green ‘Position from cookie’ button, or position it randomly with the blue ‘Position randomly’ button. Erase the cookie with the orange ‘Erase cookie’ button. Toggle easing (animation) with the Bright green button (which changes to dark red when off), it tells the current mode of ease. I have the cookie coordinates displayed and the current coordinates of the purple/yellow circle also displayed.
The cookie includes a date object, which is used to calculate the age of the cookie (watch it reset when you erase the cookie (orange button)).
The ‘All Time Visit’ stat is the only thing that does not get reset when you erase the cookie,

and source code:

  1. ////////////////////////  Initialize variables  ///////////////////////
  2.  
  3. //make Local Shared Object named myLocalSO(in as) called "myflashcookie" on disk
  4. var myLocalSO:SharedObject = SharedObject.getLocal("myflashcookie");
  5. //speed var for easing
  6. var speed = 3;
  7. var w = myCircle._width/2;
  8. //toggle var for easing
  9. var ease = true;
  10. //as var to store alltime cookie
  11. var allTimeVisitCount=0;
  12. countVisit();
  13. cookieFeedback();
  14. //line style for tracing movement
  15. lineStyle(1, 0, 50);
  16.  
  17.  
  18. ////////////////////////  Functions  ///////////////////////
  19.  
  20. //set key's value to specified value in SO
  21. //key is the name of the data
  22. //val is key's value
  23. function setVal(key, val) {
  24.   myLocalSO.data[key] = val;
  25.   trace(key +" set to "+val);
  26.   //flush the SO, write the SO to disk
  27.   myLocalSO.flush();
  28. }
  29. //get key's value from SO
  30. function getVal(key) {
  31.   return myLocalSO.data[key];
  32.   trace(myLocalSO.data[key] +" received from "+key);
  33. }
  34.  
  35. function countVisit() {
  36.   //if first visit
  37.   if (getVal('visitCount') == undefined) {
  38.     //create date for now and store in cookie
  39.     var todayDate:Date = new Date();
  40.     setVal('date', todayDate);
  41.     trace("creating date");
  42.     //start/reset counting visits
  43.     var visitCount = 0;
  44.     //notice allTimeVisitCount is not reset, but stored still as a var in actionscript
  45.   }
  46.  
  47.   //not first visit
  48.   else {
  49.     visitCount = getVal('visitCount');
  50.     allTimeVisitCount = getVal('allTimeVisitCount');
  51.   }
  52.   //increment visit counter
  53.   setVal('visitCount', visitCount+1);
  54.   setVal('allTimeVisitCount', allTimeVisitCount+1);
  55.   //feedback of visit counting
  56.   visitsFeedback.text = getVal('visitCount');
  57.   allTimeVisitsFeedback.text = getVal('allTimeVisitCount');
  58. }
  59. //feedback of cookie contents
  60. function cookieFeedback() {
  61.   //in defined print coordinate contents
  62.   cookiex.text = getVal('circleX') == undefined ? "no cookie" : getVal('circleX');
  63.   cookiey.text = getVal('circleY') == undefined ? "no cookie" : getVal('circleY');
  64.  
  65.   //if not easing assign coordinates from cookie
  66.   if (!ease) {
  67.     myCookie._x = getVal('circleX');
  68.     myCookie._y = getVal('circleY');
  69.   }
  70.   //set target to cookie coordinates
  71.   else {
  72.     ctargetx = getVal('circleX');
  73.     ctargety = getVal('circleY');
  74.   }
  75.   //if name then trace cookie contents
  76.   if (getVal('name') != undefined) {
  77.     visitorFeedback.text = "Returning Visitor";
  78.     nameInput.text = getVal('name');
  79.     ageInput.text = getVal('age');
  80.   }
  81.   //no name then a new visitor
  82.   else {
  83.     visitorFeedback.text = "First Time Visitor";
  84.     nameInput.text = "";
  85.     ageInput.text = "";
  86.   }
  87.   calculateCookieAge();
  88. }
  89. function calculateCookieAge() {
  90.   //make a date now
  91.   todayDate = new Date();
  92.   //get the cookie's stored date
  93.   cookieDate = getVal('date');
  94.   //difference between two dates
  95.   cookieDateAge = Math.floor(todayDate - cookieDate);
  96.   //convert miliseconds to a timecode
  97.   cookieAge.text = msToTimeCode(cookieDateAge);cookieDateAge;
  98. }
  99.  
  100. //convert miliseconds to a hh:mm:ss
  101. function msToTimeCode(ms) {
  102.   //make sure value is within bounds. if a number grater than zero and less than the duration of video
  103.     if (isNaN(ms) || ms< 0) {
  104.         ms = 0;
  105.     }
  106.   //find seconds
  107.   var sec = ms/1000;
  108.   //find minutes
  109.     var min = Math.floor(sec/60);
  110.   //adjust seconds
  111.     sec = sec - min*60;
  112.   //find hours
  113.   var hour = Math.floor(min/60);
  114.   //adjust minutes
  115.   min = min - hour*60;
  116.   //floor seconds down to whole number
  117.   sec = Math.floor(sec);
  118.   //make time code with hours
  119.   if (hour == 0) {
  120.     if (sec < 10) {
  121.           sec = "0"+sec;
  122.       }
  123.       if (min < 10) {
  124.           min = "0"+min;
  125.       }
  126.       var tc = min+":"+sec;
  127.   }
  128.   //make time code without hours
  129.   else {
  130.     if (sec < 10) {
  131.           sec = "0"+sec;
  132.       }
  133.       if (min < 10) {
  134.           min = "0"+min;
  135.       }
  136.       var tc = hour+":"+min+":"+sec;
  137.   }
  138.   return tc;
  139. }
  140.  
  141.  
  142.  
  143.  
  144.  
  145. //////  Actionscript attached to Objects/handlers  //////////
  146.  
  147. //place data on stage into cookie (circle coordinates and input text)
  148. setCookieButton.onRelease = function() {
  149.   setVal('circleX', myCircle._x);
  150.   setVal('circleY', myCircle._y);
  151.   setVal('name', nameInput.text);
  152.   setVal('age', ageInput.text);
  153.   //update the display on stage
  154.   cookieFeedback();
  155. }
  156. //make random coordinates on stage
  157. randomButton.onRelease = function() {
  158.   //if not easing assign coordinates to myCircle
  159.   if (!ease) {
  160.     myCircle._x = Math.random() * (Stage.width - w);
  161.     myCircle._y = Math.random() * (Stage.height - w);
  162.   }
  163.   //if easing assign coordinates to myCircle's target coords
  164.   else {
  165.     targetx = Math.random() * (Stage.width - w);
  166.     targety = Math.random() * (Stage.height - w);
  167.   }
  168. }
  169.  
  170. myCircle.onPress = function() {
  171.   this.startDrag();
  172.   dragging = true;
  173.   lineStyle(1, 200, 30);
  174. }
  175.  
  176. myCircle.onRelease = myCircle.onReleaseOutside = function() {
  177.   targetx = this._x;
  178.   targety = this._y;
  179.  
  180.   lineStyle(1, 0, 50);
  181.  
  182.   dragging = false;
  183.   this.stopDrag();
  184. }
  185.  
  186. myCircle.onEnterFrame = function() {
  187.   //print position feedback
  188.   currentx.text = this._x;
  189.   currenty.text = this._y;
  190.   //if eas move to target
  191.   if (ease) {
  192.     if (!dragging) {
  193.       moveTo(this._x+w, this._y+w);
  194.       this._x+=(targetx-this._x)/speed;
  195.       this._y+=(targety-this._y)/speed;
  196.     }
  197.     //draw line
  198.     lineTo(this._x+w, this._y+w);
  199.   }
  200. }
  201.  
  202. myCookie.onEnterFrame = function() {
  203.   //if ease move cookie to target
  204.   if (ease) {
  205.     this._x+=(ctargetx-this._x)/speed;
  206.     this._y+=(ctargety-this._y)/speed;
  207.   }
  208.   calculateCookieAge();
  209. }
  210.  
  211. //Position from Cookie
  212. cookieButton.onRelease = function() {
  213.   //if not easing set coordinates from cookie
  214.   if (!ease) {
  215.     myCircle._x = getVal('circleX');
  216.     myCircle._y = getVal('circleY');
  217.   }
  218.   //if easing set target coordinates from cookie
  219.   else {
  220.     targetx = getVal('circleX');
  221.     targety = getVal('circleY');
  222.   }
  223. }
  224. easeBtn.onRelease = function () {
  225.   //toggle easing
  226.   ease = !ease;
  227.   //advance the frame of this button...
  228.   this.play();
  229. }
  230. clearCookieBtn.onRelease = function() {
  231.   //clear the cookie (swipe all data)
  232.   myLocalSO.clear();
  233.   //restart visit count
  234.   countVisit();
  235.   //read cookie and give feedback
  236.   cookieFeedback();
  237. }

Source

download the source for this example: sharedObject.fla

Tags: , , , , , , ,

Dynamic Flash Scrolling Link List XML driven Component on FlashDen

Go get the file at FlashDen

Dynamic Scrolling Link List XML driven (No Wrap)

An interactive link list. Vertically scrolling list of links or just text. Could be used for a nav menu or a link list, or even just a scrolling list. Scroll speed calculated dynamically from mouse position to give not only scrolling control, but also speed control. Reads an external XML file containing just titles and url paths and creates this interactive click-able link list! On click the link is highlighted and on release loads the url either in a blank window or not (configurable). On rollover the list item grows with animation and is highlighted (all configurable, size speed etc). Once end of list is reached scrolling stops, another version is available with a wrap-around feature: Dynamic Scrolling Link List XML driven Auto wrapping

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Tags: , , , , , , , , , ,

Interactive Spin Actionscript Tutorial

I have been thinking of different interactions that are possible with objects. If you’ve read this blog at all you’ll know that I’ve played with physics and gravity and throwing balls and bouncing balls and all sorts. But I hadn’t wrapped my head around an interactive spinner. I know it’d be easy to make a slider or something that would apply a spin to an object, but this just isn’t interactive enough for me.

Circle with slider to rotate and button for random spin:
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

This attempt at spinning is ok. I mean, it spins the object and it even glides to a stop if you press the button for a random spin… But it’s just not intuitive and not fun. But if you want this, here’s how I did it.

Actionscript:

  1. drag = .96;
  2. speed = 0;
  3.  
  4. slider.handle.onPress = function() {
  5. spinning = false;
  6. //drag along the line
  7. this.startDrag(true, slider.line._x-slider.handle._width/2, slider.line._y-slider.handle._height/2, slider.line._width-slider.handle._width/2, slider.line._y-slider.handle._height/2);
  8. }
  9. slider.handle.onRelease = slider.handle.onReleaseOutside = function() {
  10. this.stopDrag();
  11. }
  12. _root.onEnterFrame = function() {
  13. if (spinning) {
  14. //apply the speed to the rotation
  15. knob._rotation += speed;
  16. //recalculate speed
  17. speed = speed*drag;
  18. //if speed gets unnoticeably tiny just set it to 0
  19. if (Math.pow(speed, 2) &lt; .0001) {
  20. speed = 0;
  21. }
  22. }
  23. else {
  24. //set the rotation from the slider position
  25. knob._rotation = slider.line._x + slider.handle._x + slider.handle._width/2;
  26. }
  27.  
  28. //spit out feedback continuously
  29. feedbackr.text = knob._rotation;
  30. feedbackaccr.text = speed;
  31. }
  32. spinner.onRelease = function() {
  33. //find a random speed
  34. speed = (Math.random()* 50) - 25;
  35. spinning = true;
  36. }

I want to grab it and spin it though. I want to apply the same principles from physics, like acceleration and friction as forces to the object, so I can grab to spin and release to watch it glide gracefully to a stop. I’ve been thinking about this and how I’d have to use trigonometry and stuff to do it. One day I finally had the time and tried it out. It took me a minute but I figured out that what I needed was arctangent. So (with pointers from jbum, thanks Jim!) I came up with this:

Interactive grab-able circle to spin and twirl:
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

This one is much more interactive and intuitive. I really think this is because there are no sliders or buttons, no controls, just an object to interact with. It’s much more like real life!

Steps:

In order to make a grab and spin object
1. You have to know where you grab. The user clicks on the shape (knob) and you must figure out what degree or rotation point they have started at. (atan2)
2. As the knob is clicked and the mouse moves (dragging), calculate new rotation by mouse position
3. When mouse is released figure out the current speed of rotation and apply it to the knob with friction, so it can be thrown and spun in that way. (Of course this is optional, if you just want to spin it when the mouse is down you’re done at step 2)

Actionscript:

  1. damp = .96; //friction
  2. r = 0; //rotation
  3. accr = 0; //speed of rotation
  4.  
  5. knob.onPress = function() {
  6. dragging = true;
  7. //find mouse y coordinate in relation to knob origin
  8. a = _root._ymouse - knob._y;
  9. //find mouse x coordinate in relation to knob origin
  10. b = _root._xmouse - knob._x;
  11. //using arctangent find the spot of rotation (in degrees)
  12. oldr = Math.atan2(a,b)*180/Math.PI;
  13. }
  14.  
  15. knob.onRelease = knob.onReleaseOutside = function() {
  16. dragging = false;
  17. }
  18.  
  19. knob.onEnterFrame = function() {
  20. if (dragging) {
  21. //find mouse y coordinate in relation to knob origin
  22. a = _root._ymouse-knob._y;
  23. //find mouse x coordinate in relation to knob origin
  24. b = _root._xmouse-knob._x;
  25. //using arctangent find the spot of rotation (in degrees)
  26. r = Math.atan2(a,b)*180/Math.PI;
  27.  
  28. //use current rotation and previous rotation
  29. //to find acceleration
  30. //averages the acceleration with the
  31. //previous acceleration for smoother spins
  32. accr = ((r - oldr) + accr)/2;
  33. //apply the acceleration to the rotation
  34. knob._rotation += accr;
  35. //remember current rotation as old rotation
  36. oldr = r;
  37. feedbacka.text = a;
  38. feedbackb.text = b;
  39. }
  40. else {
  41. knob._rotation += accr;
  42. //apply friction to acceleration force
  43. //and if acceleration gets tiny, just set it to zero
  44. if (Math.pow(accr, 2) &gt; .0001 ) {
  45. accr *= damp;
  46. }
  47. else{
  48. accr = 0;
  49. }
  50. }
  51. //spit out feedback continuosly
  52. feedbackr.text = knob._rotation;
  53. feedbackaccr.text = accr;
  54. }

I commented the code to explain what is happening, if you need more just post a comment. Let me know if you find this useful and what you end up making with it.

Downloads:

spin fla
interactive spin fla

Tags: , , , , , , , , , , ,

Local Connection Actionscript - Communicate between seperate Flash files | Tutorial

Overview:

Local Connection
Communication between two seperate flash files placed on the same page (or even running simultaneously on one machine) is a nice way to spread a project out. You can send variable, call functions, pretty much do anything in one swf from another. Easiest case use would be a navigation menu set up in one flash file to control the other one containing the content. I’ve made an example here showing how to send text from one to another. I’ve done it both directions here. Send text from the red swf to the blue swf, and from mr. Blue you send to the red flash file. I have named the flash functions in actionscript accordingly (or tried to, now I notice a few places I misspelled receive, ‘i’ before ‘e’, right? oh yea, except after ‘c’)…
Anyways, try out the example here, I made it a little easier by putting a keyListener on ‘Enter’, so you don’t have to actually press the send button. Didn’t realize it before, but this is like a chat app built in flash! So go ahead and chat with yourself to prove that it works!

Execute actionscript in one swf from another! Inter-swf communication.

Example:

Type here to send Red text to Blue flash file
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

And see it received here, and go ahead and send some back to Red.
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Actionscript:

Red:

  1. // Receiving
  2. //create a local connection for reciept of text
  3. var receiving_lc:LocalConnection = new LocalConnection();
  4. //function called from other swf
  5. receiving_lc.recieveBlueText = function(textRecieved:String) {
  6. feedback.text += textRecieved+"\n";
  7. };
  8. //receive connection of specified name
  9. receiving_lc.connect("fromBlue");
  10.  
  11. //Sending
  12. sendButton.onRelease = function() {
  13. //create local connection for sending text
  14. var sending_lc:LocalConnection = new LocalConnection();
  15. //put text from input into a var
  16. var textToSend = inputText.text;
  17. //send through specified connection, call specified method, send specified parameter
  18. sending_lc.send("fromRed", "recieveRedText", textToSend);
  19. //set the input empty
  20. inputText.text = "";
  21. }

Blue:

  1. // Receiving
  2. var receiving_lc:LocalConnection = new LocalConnection();
  3. receiving_lc.recieveRedText = function(textRecieved:String) {
  4. feedback.text += textRecieved+"\n";
  5. };
  6. receiving_lc.connect("fromRed");
  7.  
  8. //Sending
  9. sendButton.onRelease = function() {
  10. var sending_lc:LocalConnection = new LocalConnection();
  11. var textToSend = inputText.text;
  12. sending_lc.send("fromBlue", "recieveBlueText", textToSend);
  13. inputText.text = "";
  14. }

And the code to listen to the ‘enter’ key(this is in both files):

  1. //Enter button to send
  2. var keyListener:Object = new Object();
  3. keyListener.onKeyDown = function() {
  4. if (Key.getCode() == "13") {
  5. sendButton.onRelease();
  6. }
  7. };
  8. Key.addListener(keyListener);

Download Source:

localConnectionRedBlue.zip

Tags: , , , , , ,

Men Circles | Interactive Experiment

Here’s a graphic of a circle of men. You may recognize the outline from any public restroom. They’re standing in a corny circle holding hands, like an all over the world theme., let’s just hope they all washed their hands…

I made the graphic a while ago, and have been wanting to interactive-ize it. I’ve really been wanting to play with elasticity, throwing things and snapping to a point… Although I’m still thinking about a version where I’d spin the objects rather than just throw them, I figured I’d put it up for any feedback that comes.

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

The different pieces all rotate differently and it changes if you are dragging or ‘holding’ them. Then you can press the anchor (gray) button to toggle the snap. The objects will all center around the anchor and spring into place (elasticity applied to position and rotation). And then the interactivity changes and rather than dragging and dropping them, you push and bump or throw them. It almost turns into a game…

Here’s some of the actionscript

  1. _root.tr = 0;
  2. _root.k = 0.2;
  3. _root.damp = .9;
  4. _root.margin = 150;
  5. _root.heads.ax = 0;
  6. _root.heads.vx = 0;
  7. _root.heads.ay = 0;
  8. _root.heads.vy = 0;
  9. _root.heads.ar = 0;
  10. _root.heads.vr = 0;
  11. _root.heads._x = (Math.random() * (Stage.width + _root.heads._width)) - _root.margin;
  12. _root.heads._y = (Math.random() * (Stage.height + _root.heads._height)) - _root.margin;
  13.  
  14. //Heads
  15. _root.heads.dragging = false;
  16. _root.heads.onEnterFrame = function() {
  17. if (!_root.center.dragging){
  18. if (_root.heads.dragging){
  19. this._rotation += 1.2;
  20. }
  21. else {
  22. rot = this._rotation + Math.random();
  23. xmouse = _root._xmouse/Stage.width;
  24. this._rotation += rot + xmouse;
  25. }
  26.  
  27. this._x+=Math.random()*2 - 1;
  28. this._y+=Math.random()*2 - 1;
  29.  
  30. }
  31. else {
  32. //_root.heads._x = _root.center._x;
  33. //_root.heads._y = _root.center._y;
  34. _root.heads.ax = (_root.center._x - _root.heads._x) * _root.k;
  35. _root.heads.vx += _root.heads.ax;
  36. _root.heads.vx *= _root.damp;
  37. _root.heads._x += _root.heads.vx;
  38.  
  39. _root.heads.ay = (_root.center._y - _root.heads._y) * _root.k;
  40. _root.heads.vy += _root.heads.ay;
  41. _root.heads.vy *= _root.damp;
  42. _root.heads._y += _root.heads.vy;
  43.  
  44. _root.heads.ar = (_root.tr - _root.heads._rotation) * _root.k;
  45. _root.heads.vr += _root.heads.ar;
  46. _root.heads.vr *= _root.damp;
  47. _root.heads._rotation+=_root.heads.vr;
  48. }
  49. this.onPress = function() {
  50. startDrag(this, false);
  51. _root.heads.dragging = true;
  52. }
  53. this.onRelease = this.onReleaseOutside = function() {
  54. stopDrag();
  55. _root.heads.dragging = false;
  56. }
  57. this.onRollOver = function() {
  58. if(_root.center.dragging){
  59. startDrag(this, false);
  60. _root.heads.dragging = true;
  61. }
  62. }
  63. this.onRollOut = function() {
  64. if(_root.center.dragging) {
  65. stopDrag();
  66. _root.heads.dragging = false;
  67. }
  68. }
  69. }
  70.  
  71. //Button
  72. _root.center.dragging = false;
  73. _root.center.onEnterFrame = function() {
  74. this.onPress = function() {
  75. startDrag(_root.center, false);
  76. _root.center.dragging = !_root.center.dragging;
  77. if (_root.center.dragging) {
  78. this.gotoAndStop("on");
  79. }
  80. else {
  81. this.gotoAndStop("off");
  82. }
  83.  
  84. //var vr:Number = 0;
  85. }
  86. this.onRelease = this.onReleaseOutside = function () {
  87. stopDrag();
  88. //_root.center.dragging = false;
  89. }
  90. }

Tags: , , , , , ,

Dynamic Flash Vertical Scrolling Link List with XML download at Flashden

Go get the source files at Flashden

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

circlecube on FlashDen

Tags: , , , , , , , , , ,

Distance Formula in Actionscript Tutorial | Pythagorean theorem

Overview

To find the distance of any two points on an axis is easy, just subtract them. But what about when you have to find the distance of something not on the axis (a diagonal)? Find the distance between any two points with the Pythagorean theorem. This is an old problem we can look to history and find the Pythagorean theorem and Pythagoras, the Greek we’ve named this after. His theorem states that ‘In any right triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).’
pythagorean img

You may remember it as the formula you memorized in geometry or algebra class ‘a squared plus b squared equals c squared’
a^2 + b^2 = c^2
pythag equ

Okay, but how does that help in flash? You want to find the distance between point a and point b. Well c would be the distance between the two points. We know the formula, solving for c.
c = square root of (a^2 + b^2).
pythag equ 2
c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
Math.sqrt()
is the square root function, so Math.sqrt(4)=2.
Math.sqrt(x) computes and returns the square root of x.
Math.pow() is the power function, so Math.pow(4, 2)=16 (4 squared). Math.pow(x, y) computes and returns x to the power of y.

You say I remember using this for triangles and stuff, I just want to know the distance between two points, there’s no triangles.
Well, there actually is a triangle we can draw. Go from your first, along an axis (this makes one side), and the other point, along the other axis (this is another side), and you’ll see that the distance you’re looking for is the third side of the triangle (the hypotenuse).

Example

Here’s a quick interactive flash file to show the idea.
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Actionscript

  1. xmid = Stage.width/2;
  2. ymid = Stage.height/2;
  3. a = _root._ymouse-ymid;
  4. b = _root._xmouse-xmid;
  5. c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
  6. feedbacka.text = Math.round(a);
  7. feedbackb.text = Math.round(b);
  8. feedbackc.text = Math.round(c);

Download

As usual, here’s the source flash file (flash 8 compatible) to take a look: distance.fla

Tags: , , , , , , ,
Next entries »