PageRenderTime 107ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Game2D/Game.as

https://bitbucket.org/toxicFork/game2dflash
ActionScript | 275 lines | 188 code | 53 blank | 34 comment | 19 complexity | 266610b88d320648a8b443293f6f340c MD5 | raw file
  1. package Game2D {
  2. import Box2D.Collision.Shapes.b2PolygonShape;
  3. import Box2D.Collision.Shapes.b2Shape;
  4. import Box2D.Collision.b2AABB;
  5. import Box2D.Common.Math.b2Vec2;
  6. import Box2D.Dynamics.Joints.b2MouseJoint;
  7. import Box2D.Dynamics.Joints.b2MouseJointDef;
  8. import Box2D.Dynamics.b2Body;
  9. import Box2D.Dynamics.b2DebugDraw;
  10. import Box2D.Dynamics.b2Fixture;
  11. import Box2D.Dynamics.b2World;
  12. import flash.display.Bitmap;
  13. import flash.display.BitmapData;
  14. import flash.display.Sprite;
  15. import flash.events.Event;
  16. import flash.geom.Matrix;
  17. import flash.geom.Point;
  18. import flash.utils.getTimer;
  19. [SWF(width='640', height='480', frameRate="120")]
  20. public class Game extends StageSprite {
  21. protected var view:View;
  22. protected var world:b2World;
  23. protected var drawSprite:Sprite;
  24. public static var physicsScale:Number = 30.0;
  25. private const velocityIterations:int = 10;
  26. private const positionIterations:int = 10;
  27. private var mouseJoint:b2MouseJoint;
  28. private var bitmapData:BitmapData;
  29. private var bitmap:Bitmap;
  30. protected var mouseCoords:Point2D;
  31. //private var rot:Number = 0.0;
  32. //private var scale:Number = 1.0;
  33. private var lastTime:Number;
  34. private var dbgDraw:b2DebugDraw;
  35. public static var debugSprite:Sprite;
  36. protected var debug:Boolean;
  37. protected var rendering:Boolean = true;
  38. private var displayMatrix:Matrix;
  39. private var invertedDisplayMatrix:Matrix;
  40. public function Game(debug:Boolean = true) {
  41. this.debug = debug;
  42. addEventListener(GameEvent.INITIALISE,initialiseWorld);
  43. super();
  44. }
  45. private function initialiseWorld(event:GameEvent):void {
  46. drawSprite = new Sprite();
  47. debugSprite = new Sprite();
  48. bitmapData = new BitmapData(stage.stageWidth,stage.stageHeight);
  49. bitmap = new Bitmap(bitmapData);
  50. addChild(bitmap);
  51. //var worldAABB:b2AABB = new b2AABB();
  52. //worldAABB.lowerBound.Set(-1000.0, -1000.0);
  53. //worldAABB.upperBound.Set(1000.0, 1000.0);
  54. // Define the gravity vector
  55. var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);
  56. // Allow bodies to sleep
  57. var doSleep:Boolean = true;
  58. // Construct a world object
  59. world = new b2World(gravity, doSleep);
  60. //world.SetBroadPhase(new b2BroadPhase(worldAABB));
  61. world.SetWarmStarting(true);
  62. //if(debug)
  63. {
  64. // set debug draw
  65. dbgDraw = new b2DebugDraw();
  66. dbgDraw.SetSprite(drawSprite);
  67. dbgDraw.SetDrawScale(physicsScale);
  68. dbgDraw.SetFillAlpha(0.3);
  69. dbgDraw.SetLineThickness(1.0);
  70. dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
  71. world.SetDebugDraw(dbgDraw);
  72. }
  73. world.SetContactListener(new ContactListener());
  74. view = new View();
  75. view.position = new Point2D(0, 0);
  76. view.rect = new Rect(0,0,stage.stageWidth,stage.stageHeight);
  77. view.rotation = 0.0;
  78. view.scale = 1.0;
  79. Input.RegisterEvents(stage);
  80. stage.addEventListener(Event.ENTER_FRAME,update);
  81. stage.addEventListener(Event.RESIZE,reSized);
  82. reSized(null);
  83. dispatchEvent(new GameEvent(GameEvent.START));
  84. }
  85. private function reSized(event:Event):void {
  86. const offset:Number = -2;
  87. view.rect = new Rect(-offset,-offset,stage.stageWidth-offset*2,stage.stageHeight-offset*2).Times(1/physicsScale);
  88. bitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
  89. bitmap.bitmapData = bitmapData;
  90. }
  91. private function update(event:Event):void {
  92. var curTime:Number = getTimer() / 1000.0;
  93. var deltaTime:Number = curTime - lastTime;
  94. // Update physics
  95. world.Step(deltaTime, velocityIterations, positionIterations);
  96. world.ClearForces();
  97. updateWorld(deltaTime);
  98. var worldObject:WorldObject;
  99. for (var body:b2Body = world.GetBodyList(); body; body = body.GetNext()) {
  100. worldObject = body.GetUserData() as WorldObject;
  101. if (worldObject) {
  102. worldObject.doUpdate(deltaTime);
  103. }
  104. }
  105. updateViewMatrix();
  106. bitmapData.fillRect(bitmapData.rect, 0);
  107. var center:Point2D = new Point2D(stage.stageWidth / 2, stage.stageHeight / 2);
  108. if (rendering)
  109. view.RenderInto(world, bitmapData, center);
  110. //for (var i:uint = 0; i < numObjects; i++) {
  111. // objects[i].update(curTime - lastTime);
  112. // }
  113. if (debug) {
  114. dbgDraw.SetLineThickness(view.scale);
  115. // Render
  116. world.DrawDebugData();
  117. }
  118. else {
  119. drawSprite.graphics.clear();
  120. }
  121. // if(mouseCoords&&viewShape)
  122. // if(viewShape.TestPoint(world.GetGroundBody().GetTransform(), mouseCoords.Times(1/physicsScale).vec))
  123. // {
  124. // drawSprite.graphics.lineStyle(1,Color.Black);
  125. // drawSprite.graphics.moveTo(view.rect.center.x*physicsScale, view.rect.center.y*physicsScale);
  126. // var pos:Point2D = mouseCoords;
  127. // drawSprite.graphics.lineTo(pos.x, pos.y);
  128. // }
  129. for (body = world.GetBodyList(); body; body = body.GetNext()) {
  130. worldObject = body.GetUserData() as WorldObject;
  131. if (worldObject) {
  132. worldObject.render(drawSprite.graphics, view);
  133. }
  134. }
  135. //drawSprite.graphics.lineStyle(player.scale, Color.Black, 1);
  136. //drawSprite.graphics.drawCircle(player.pos.x * physicsScale, player.pos.y * physicsScale, 5.0 * player.scale);
  137. renderWorld();
  138. //for (var i = 0; i < numObjects; i++) {
  139. // objects[i].render(drawSprite.graphics, view, physicsScale);
  140. //}
  141. bitmapData.draw(drawSprite, displayMatrix);
  142. bitmapData.draw(debugSprite, displayMatrix);
  143. //matrix.invert();
  144. mouseCoords = Point2D.FromPoint(invertedDisplayMatrix.transformPoint(new Point(bitmap.mouseX, bitmap.mouseY)));
  145. mouseDrag();
  146. lastTime = curTime;
  147. }
  148. private function updateViewMatrix():void {
  149. updateView();
  150. view.UpdateMatrices();
  151. var center:Point2D = new Point2D(stage.stageWidth/2,stage.stageHeight/2);
  152. displayMatrix = view.matrix.clone();
  153. displayMatrix.translate(center.x, center.y);
  154. invertedDisplayMatrix = displayMatrix.clone();
  155. invertedDisplayMatrix.invert();
  156. }
  157. //noinspection JSUnusedGlobalSymbols
  158. protected function convertCoords(coords:Point2D):Point2D {
  159. if (displayMatrix == null)
  160. updateViewMatrix();
  161. return Point2D.FromPoint(invertedDisplayMatrix.transformPoint(coords.point));
  162. }
  163. protected function renderWorld():void {}
  164. //noinspection JSUnusedLocalSymbols
  165. protected function updateWorld(deltaTime:Number):void {}
  166. protected function updateView():void {}
  167. private function mouseDrag():void {
  168. if(Input.mouseDown&&!mouseJoint)
  169. {
  170. var body:b2Body = getBodyAtMouse();
  171. if(body)
  172. {
  173. var md:b2MouseJointDef = new b2MouseJointDef();
  174. md.bodyA = world.GetGroundBody();
  175. md.bodyB = body;
  176. md.target.Set(mouseCoords.x/physicsScale,mouseCoords.y/physicsScale);
  177. md.collideConnected = true;
  178. md.maxForce = 300.0 * body.GetMass();
  179. mouseJoint = world.CreateJoint(md) as b2MouseJoint;
  180. body.SetAwake(true);
  181. }
  182. }
  183. if(!Input.mouseDown)
  184. {
  185. if(mouseJoint)
  186. {
  187. world.DestroyJoint(mouseJoint);
  188. mouseJoint = null;
  189. }
  190. }
  191. if(mouseJoint)
  192. {
  193. mouseJoint.SetTarget(new b2Vec2(mouseCoords.x/physicsScale,mouseCoords.y/physicsScale));
  194. }
  195. }
  196. public function getBodyAtMouse(includeStatic:Boolean = false):b2Body {
  197. // Make a small box.
  198. var mousePVec:b2Vec2 = new b2Vec2(mouseCoords.x/physicsScale, mouseCoords.y/physicsScale);
  199. var aabb:b2AABB = new b2AABB();
  200. aabb.lowerBound.Set(mousePVec.x - 0.001, mousePVec.y - 0.001);
  201. aabb.upperBound.Set(mousePVec.x + 0.001, mousePVec.y + 0.001);
  202. var body:b2Body = null;
  203. // Query the world for overlapping shapes.
  204. function GetBodyCallback(fixture:b2Fixture):Boolean
  205. {
  206. var shape:b2Shape = fixture.GetShape();
  207. if (!fixture.IsSensor() && (fixture.GetBody().GetType() != b2Body.b2_staticBody || includeStatic))
  208. {
  209. var inside:Boolean = shape.TestPoint(fixture.GetBody().GetTransform(), mousePVec);
  210. if (inside)
  211. {
  212. body = fixture.GetBody();
  213. return false;
  214. }
  215. }
  216. return true;
  217. }
  218. world.QueryAABB(GetBodyCallback, aabb);
  219. return body;
  220. }
  221. }
  222. }