Category Archives: misc

nesting(function(calls()))

Actionscript:
  1. [SWF(width=500, height=500, backgroundColor=0x000000, frameRate=30)]
  2.  
  3. for (var i:int = 0; i<10; i++){
  4.        // draggable ellipse
  5.     var dot:Sprite = drag(createSprite("Ellipse",  -10, -10, 20, 20));
  6.     dot.x = Math.random() * stage.stageWidth ;
  7.     dot.y = Math.random() * stage.stageHeight ;
  8. }
  9.  
  10. for (i = 0; i<10; i++){
  11.  
  12.       var box:Sprite = drag(spin(createSprite("Rect", -20, -20, 40, 40, 0xFF0000), Math.random()*5 + 1));
  13.     box.x = Math.random() * stage.stageWidth ;
  14.     box.y = Math.random() * stage.stageHeight ;
  15. }
  16.  
  17.  
  18.  // createSprite can create ellipses or rectangles
  19. function createSprite(shape:String, xp:Number, yp:Number, w:Number, h:Number, col:uint=0x444444):Sprite {
  20.     var s:Sprite = new Sprite();
  21.     s.graphics.beginFill(col);
  22.     // trick from a previous post
  23.     s.graphics["draw" + shape](xp, yp, w, h);
  24.     addChild(s);
  25.     return s;
  26. }
  27.  
  28. // drag and spin add listeners to an untyped target and return that target for easy function nesting
  29. function drag(target:*):*{
  30.     target.addEventListener(MouseEvent.MOUSE_DOWN, function(evt:MouseEvent){ evt.currentTarget.startDrag(); });
  31.     return target;
  32. }
  33.  
  34. function spin(target:*, speed:Number):*{
  35.     target.addEventListener(Event.ENTER_FRAME, function(evt:Event){ evt.currentTarget.rotation+=speed; });
  36.     return target;
  37. }
  38.  
  39. stage.addEventListener(MouseEvent.MOUSE_UP, function(){ stopDrag() });

The above will create some draggable circles and some rotating draggable rects... but that's not really the point....

When prototyping and just playing around I write functions that take an Object as an argument, alter that Object in some way and pass that some Object out as a return value.... this makes it so I can write things like this:

Actionscript:
  1. drag(spin(createSprite("Rect", -20, -20, 40, 40, 0xFF0000), Math.random()*5 + 1));

Readability can be a problem so... consider that before using this for anything...

Also posted in dynamic, functions | Tagged , | Leave a comment

Script List Pattern

Actionscript:
  1. var currentState:String = "";
  2.  
  3. var functionList:Vector.<Function> = new Vector.<Function>();
  4.  
  5. function clearFunctions():void{
  6.     functionList = new Vector.<Function>();
  7. }
  8. function addFunction(f:Function):Function {
  9.     functionList.push(f);
  10.     return addFunction;
  11. }
  12.  
  13. function removeFunction(f:Function):void {
  14.     for (var i:int = 0 ; i<functionList.length; i++){
  15.         if (f == functionList[i]){
  16.             functionList.splice(i, 1);
  17.         }
  18.     }
  19. }
  20.  
  21. function runProgram():void {
  22.    
  23.     currentState = "current: ";
  24.    
  25.     for (var i:int = 0; i<functionList.length; i++){
  26.         functionList[i]();
  27.     }
  28.    
  29.     trace(currentState);
  30. }
  31.  
  32. function one():void{
  33.     currentState += " one";
  34. }
  35.  
  36. function two():void {
  37.     currentState += " two";
  38. }
  39.  
  40. function three():void {
  41.     currentState += " three";
  42. }
  43.  
  44. function dot():void{
  45.     currentState += ".";
  46.    
  47. }
  48.  
  49. // test it:
  50. addFunction(one);
  51. addFunction(two);
  52. addFunction(three);
  53.  
  54. runProgram();
  55.  
  56. removeFunction(one);
  57.  
  58. runProgram();
  59.  
  60. addFunction(dot)(dot)(dot);
  61.  
  62. runProgram();
  63.  
  64. clearFunctions();
  65.  
  66. addFunction(dot)(dot)(dot);
  67.  
  68. addFunction(three)(two)(one)(dot)(dot)(dot);
  69.  
  70. runProgram();
  71.  
  72. /* outputs:
  73. current:  one two three
  74. current:  two three
  75. current:  two three...
  76. current: ... three two one...
  77. */

This is a very quick implementation of a pattern that I use sometimes. The idea of this pattern is very simple and can easily be implemented in OOP or procedural style programming. The idea is to have a Vector/Array of functions or Class instances. Loop through this Vector/Array and run each function (or a given method of each Class instance). During runtime your client code can alter this list to change what the program does.

I use this technique for games quite often. All enemies get added to an enemy list - this list is looped through and each enemies run() method is called. If an enemy dies it dispatches an event that tells the enemy manager to remove it from the list. Some pseudo code:

Actionscript:
  1. function onMainLoop():void{
  2.     if (!paused){
  3.        
  4.         runWorld();
  5.         runKeys();
  6.         runChar();
  7.        
  8.         enemyManager.runEnemies();
  9.        
  10.         runPickups();
  11.        
  12.     }else{
  13.         // show pause screen
  14.     }
  15. }
  16.  
  17. //... inside EnemyManager class
  18. function onRunEnemies():void{
  19.     for (var i:int = 0; i<enemyList.length; i++){
  20.             enemyList[i].run(i);
  21.     }
  22. }

I use the same technique for pickups (coins, lives etc....).

I first used this technique in Director with a list of parent scripts.

I'm aware of other more refined patterns that are meant to do similar things, but for small to medium sized apps this has worked very nicely for me.

Also posted in Vector, arrays | Tagged , | 2 Comments

BitmapData Trails

Actionscript:
  1. [SWF(width=400, height=400, backgroundColor=0xCCCCCC, frameRate=30)]
  2.  
  3. var canvas:BitmapData = new BitmapData(400, 400, true, 0xCCCCCC);
  4. var eraser:BitmapData = new BitmapData(400, 400, true, 0x22CCCCCC);
  5. addChild(new Bitmap(canvas));
  6.  
  7. var circle:Shape = Shape(addChild(new Shape()));
  8. with (circle.graphics) beginFill(0x000000), drawCircle(0,0,20);
  9.  
  10. addEventListener(Event.ENTER_FRAME, onLoop);
  11.  
  12. function onLoop(evt:Event):void {
  13.     canvas.copyPixels(eraser, eraser.rect, new Point(0,0), null, null, true);
  14.     circle.x = mouseX;
  15.     circle.y = mouseY;
  16.    
  17.     canvas.draw(circle, circle.transform.matrix);
  18. }

Create trails by slowly erasing the background with copyPixels(). The first time I ever saw this technique was back when setpixel.com contained a bunch of great director experiments by Charles Foreman (creator of iminlikewithyou.com).

At some point last semester I showed iminlikewithyou hamster battle to my undergrad students towards the end of class.... probably one of the funniest moments of that class.

Also posted in BitmapData | Tagged , | 1 Comment

Jumping on a 2D Circle

Actionscript:
  1. var circle:Shape = Shape(addChild(new Shape()));
  2. with(circle.graphics) beginFill(0xCCCCCC), drawCircle(0,0,100);
  3. circle.x = stage.stageWidth / 2;
  4. circle.y = stage.stageHeight / 2;
  5.  
  6. var charWorld:MovieClip = MovieClip(addChild(new MovieClip()));
  7. charWorld.x = circle.x ;
  8. charWorld.y = circle.y - 100 - 10
  9. charWorld.thetaSpeed = 0;
  10. charWorld.theta  = -Math.PI / 2;
  11.  
  12. var char:MovieClip = MovieClip(charWorld.addChild(new MovieClip))
  13. with(char.graphics) beginFill(0x000000), drawRect(-10,-10,10,10);
  14. char.posY = 0;
  15. char.velY = 0;
  16.  
  17. addEventListener(Event.ENTER_FRAME, onRunChar);
  18. function onRunChar(evt:Event):void {
  19.    
  20.     char.velY += 1;
  21.     char.posY += char.velY;
  22.    
  23.     charWorld.thetaSpeed *= .6;
  24.     charWorld.theta += charWorld.thetaSpeed;
  25.    
  26.     if (key[Keyboard.UP]){
  27.         if (char.y == 0){
  28.           char.velY = -10;
  29.         }
  30.     }
  31.    
  32.     if (key[Keyboard.RIGHT]){
  33.         charWorld.thetaSpeed = .1;
  34.     }
  35.    
  36.     if (key[Keyboard.LEFT]){
  37.         charWorld.thetaSpeed = -.1;
  38.     }
  39.    
  40.     if (char.posY> 0){
  41.         char.posY = 0;
  42.     }
  43.    
  44.     char.y = char.posY;
  45.    
  46.     charWorld.x = circle.x + 100 * Math.cos(charWorld.theta);
  47.     charWorld.y = circle.y + 100 * Math.sin(charWorld.theta);
  48.     charWorld.rotation = Math.atan2(circle.y- charWorld.y, circle.x - charWorld.x) / Math.PI * 180 - 90;
  49. }
  50.  
  51. var key:Object = new Object();
  52. stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
  53. stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
  54. function onKeyPressed(evt:KeyboardEvent):void {
  55.     key[evt.keyCode] = true;
  56.     key.keyCode = evt.keyCode;
  57. }
  58.  
  59. function onKeyReleased(evt:KeyboardEvent):void {
  60.     key[evt.keyCode] = false
  61. }

For some reason I felt like posting the swf.... have a look here.

This is one that's been kicking around in my head for awhile - finally got around to writing it. It creates a circle and a small black box. The box walks and jumps on the circle with key input (left arrow, right arrow and up arrow).

There's an odd trick going on here. Basically, the box (or char) movieClip is nested inside another clip. Within this clip (charWorld) the box moves on the y axis (jumping/up key). The charWorld clip orbits around the circle and rotates toward the center of the circle - sine/cosine are used for the orbit so the left and the right keys control the speed of theta.

Also posted in motion | Tagged , | Leave a comment