Posted By

steppannws on 09/02/11


Tagged

camera 2d


Versions (?)

Camera 2D


 / Published in: ActionScript 3
 

A simple Camera 2d simulation in Flash

  1. package
  2. {
  3. import flash.display.MovieClip;
  4. import flash.display.Sprite;
  5. import flash.events.Event;
  6. import flash.geom.Matrix;
  7.  
  8. public class Camera extends MovieClip
  9. {
  10. private var mainCont:Sprite;
  11. private var stageW:Number;
  12. private var stageH:Number;
  13. private var camW:Number = 800; //Width of camera
  14. private var camH:Number = 600; //Height of camera
  15. private var cam:Sprite;
  16.  
  17. public function Camera(mainCont:Sprite)
  18. {
  19. this.mainCont = mainCont;
  20.  
  21. cam = new Sprite();
  22. cam.graphics.beginFill(0xFF0000, 0);
  23. cam.graphics.drawRect( -camW * .5, -camH * .5, camW, camH);
  24. cam.graphics.endFill();
  25. addChild(cam);
  26.  
  27. init();
  28. }
  29.  
  30. private function init():void
  31. {
  32. stageW = mainCont.stage.stageWidth;
  33. stageH = mainCont.stage.stageHeight;
  34.  
  35. addEventListener(Event.REMOVED_FROM_STAGE, dispose);
  36. addEventListener(Event.ENTER_FRAME, update);
  37. dispatchEvent(new Event(Event.ENTER_FRAME));
  38. }
  39.  
  40. private function update(e:Event):void
  41. {
  42. if (!mainCont) return;
  43.  
  44. var w:Number = this.width * this.scaleX;
  45. var h:Number = this.height * this.scaleY;
  46.  
  47. var sX:Number = stageW / w;
  48. var sY:Number = stageH / h;
  49.  
  50. var matrix:Matrix = this.transform.matrix.clone();
  51. matrix.invert();
  52. matrix.scale(cam.scaleX, cam.scaleY);
  53. matrix.translate(w * .5, h * .5);
  54. matrix.scale(sX, sY);
  55.  
  56. mainCont.transform.matrix = matrix;
  57. mainCont.transform.colorTransform = this.transform.colorTransform;
  58. mainCont.filters = this.filters;
  59. }
  60.  
  61. private function dispose(e:Event):void
  62. {
  63. removeEventListener(Event.REMOVED_FROM_STAGE, dispose);
  64. removeEventListener(Event.ENTER_FRAME, update);
  65.  
  66. removeChild(cam);
  67. cam = null;
  68. }
  69. }
  70. }

Report this snippet  

You need to login to post a comment.