STORY   LOOP   FURRY   PORN   GAMES
• C •   SERVICES [?] [R] RND   POPULAR
Archived flashes:
229595
/disc/ · /res/     /show/ · /fap/ · /gg/ · /swf/P0001 · P2595 · P5190

<div style="position:absolute;top:-99px;left:-99px;"><img src="http://swfchan.com:57475/43689596?noj=FRM43689596-22DC" width="1" height="1"></div>

tmnt_dd.swf

This is the info page for
Flash #214574

(Click the ID number above for more basic data on this flash file.)


Text
I’VE UNCOVERED
A WAREHOUSE BY 4TH
AND HAMILTON WITH
THE FOOT SWARMING
ALL OVER IT.

APRIL?

THE LINE WENT DEAD.

LET'S ROLL.

IT'S GONNA BLOW!

RUN!!!

COWABUNGA!

I LOVE IT WHEN
THAT HAPPENS.

ANOTHER JOB
WELL DONE.

THE END

WHAT THE SHELL?!

LOOK OUT!

PREPARE YOURSELVES,
BROTHERS!

AWW MAN...
NOT THIS GUY AGAIN.

MASTER WILL BE
PLEASED WHEN I HAVE
CRUSHED YOU.

THE FOOT ARE ESCAPING
INTO THE WAREHOUSE!

WE'RE GOING IN.

I LOVE WAREHOUSES...
SO MANY BOXES TO SMASH
BAD GUYS INTO.

I WILL NOT ALLOW
YOU MUTANT FREAKS TO
STAND IN MY WAY.

NEXT

ActionScript [AS3]

Section 1
//b2CircleDef (Box2D.Collision.Shapes.b2CircleDef) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; public class b2CircleDef extends b2ShapeDef { public var radius:Number; public var localPosition:b2Vec2; public function b2CircleDef(){ localPosition = new b2Vec2(0, 0); super(); type = b2Shape.e_circleShape; radius = 1; } } }//package Box2D.Collision.Shapes
Section 2
//b2CircleShape (Box2D.Collision.Shapes.b2CircleShape) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2CircleShape extends b2Shape { b2internal var m_localPosition:b2Vec2; b2internal var m_radius:Number; public function b2CircleShape(def:b2ShapeDef){ m_localPosition = new b2Vec2(); super(def); var circleDef:b2CircleDef = (def as b2CircleDef); m_type = e_circleShape; m_localPosition.SetV(circleDef.localPosition); m_radius = circleDef.radius; } override public function TestSegment(transform:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ var sY:Number; var tMat:b2Mat22 = transform.R; var positionX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var positionY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); var sX:Number = (segment.p1.x - positionX); sY = (segment.p1.y - positionY); var b:Number = (((sX * sX) + (sY * sY)) - (m_radius * m_radius)); if (b < 0){ lambda[0] = 0; return (e_startsInsideCollide); }; var rX:Number = (segment.p2.x - segment.p1.x); var rY:Number = (segment.p2.y - segment.p1.y); var c:Number = ((sX * rX) + (sY * rY)); var rr:Number = ((rX * rX) + (rY * rY)); var sigma:Number = ((c * c) - (rr * b)); if ((((sigma < 0)) || ((rr < Number.MIN_VALUE)))){ return (e_missCollide); }; var a:Number = -((c + Math.sqrt(sigma))); if ((((0 <= a)) && ((a <= (maxLambda * rr))))){ a = (a / rr); lambda[0] = a; normal.x = (sX + (a * rX)); normal.y = (sY + (a * rY)); normal.Normalize(); return (e_hitCollide); }; return (e_missCollide); } override public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ var p:b2Vec2 = b2Math.b2MulX(xf, m_localPosition); var l:Number = -((b2Math.b2Dot(normal, p) - offset)); if (l < (-(m_radius) + Number.MIN_VALUE)){ return (0); }; if (l > m_radius){ c.SetV(p); return (((Math.PI * m_radius) * m_radius)); }; var r2:Number = (m_radius * m_radius); var l2:Number = (l * l); var area:Number = ((r2 * (Math.asin((l / m_radius)) + (Math.PI / 2))) + (l * Math.sqrt((r2 - l2)))); var com:Number = (((-2 / 3) * Math.pow((r2 - l2), 1.5)) / area); c.x = (p.x + (normal.x * com)); c.y = (p.y + (normal.y * com)); return (area); } public function GetLocalPosition():b2Vec2{ return (m_localPosition); } public function GetRadius():Number{ return (m_radius); } override public function ComputeMass(massData:b2MassData):void{ massData.mass = (((m_density * b2Settings.b2_pi) * m_radius) * m_radius); massData.center.SetV(m_localPosition); massData.I = (massData.mass * (((0.5 * m_radius) * m_radius) + ((m_localPosition.x * m_localPosition.x) + (m_localPosition.y * m_localPosition.y)))); } override public function ComputeSweptAABB(aabb:b2AABB, transform1:b2XForm, transform2:b2XForm):void{ var tMat:b2Mat22; tMat = transform1.R; var p1X:Number = (transform1.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var p1Y:Number = (transform1.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); tMat = transform2.R; var p2X:Number = (transform2.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var p2Y:Number = (transform2.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); aabb.lowerBound.Set((((p1X < p2X)) ? p1X : p2X - m_radius), (((p1Y < p2Y)) ? p1Y : p2Y - m_radius)); aabb.upperBound.Set((((p1X > p2X)) ? p1X : p2X + m_radius), (((p1Y > p2Y)) ? p1Y : p2Y + m_radius)); } override b2internal function UpdateSweepRadius(center:b2Vec2):void{ var dX:Number = (m_localPosition.x - center.x); var dY:Number = (m_localPosition.y - center.y); dX = Math.sqrt(((dX * dX) + (dY * dY))); m_sweepRadius = ((dX + m_radius) - b2Settings.b2_toiSlop); } override public function ComputeAABB(aabb:b2AABB, transform:b2XForm):void{ var tMat:b2Mat22 = transform.R; var pX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var pY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); aabb.lowerBound.Set((pX - m_radius), (pY - m_radius)); aabb.upperBound.Set((pX + m_radius), (pY + m_radius)); } override public function TestPoint(transform:b2XForm, p:b2Vec2):Boolean{ var tMat:b2Mat22 = transform.R; var dX:Number = (transform.position.x + ((tMat.col1.x * m_localPosition.x) + (tMat.col2.x * m_localPosition.y))); var dY:Number = (transform.position.y + ((tMat.col1.y * m_localPosition.x) + (tMat.col2.y * m_localPosition.y))); dX = (p.x - dX); dY = (p.y - dY); return ((((dX * dX) + (dY * dY)) <= (m_radius * m_radius))); } } }//package Box2D.Collision.Shapes
Section 3
//b2EdgeChainDef (Box2D.Collision.Shapes.b2EdgeChainDef) package Box2D.Collision.Shapes { public class b2EdgeChainDef extends b2ShapeDef { public var vertices:Array; public var vertexCount:int; public var isALoop:Boolean; public function b2EdgeChainDef(){ super(); type = b2Shape.e_edgeShape; vertexCount = 0; isALoop = true; vertices = []; } } }//package Box2D.Collision.Shapes
Section 4
//b2EdgeShape (Box2D.Collision.Shapes.b2EdgeShape) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2EdgeShape extends b2Shape { b2internal var m_v1:b2Vec2; b2internal var m_v2:b2Vec2; private var s_supportVec:b2Vec2; b2internal var m_coreV1:b2Vec2; b2internal var m_coreV2:b2Vec2; b2internal var m_prevEdge:b2EdgeShape; b2internal var m_direction:b2Vec2; b2internal var m_cornerConvex1:Boolean; b2internal var m_cornerConvex2:Boolean; b2internal var m_cornerDir1:b2Vec2; b2internal var m_cornerDir2:b2Vec2; b2internal var m_nextEdge:b2EdgeShape; b2internal var m_normal:b2Vec2; b2internal var m_length:Number; public function b2EdgeShape(v1:b2Vec2, v2:b2Vec2, def:b2ShapeDef){ s_supportVec = new b2Vec2(); m_v1 = new b2Vec2(); m_v2 = new b2Vec2(); m_coreV1 = new b2Vec2(); m_coreV2 = new b2Vec2(); m_normal = new b2Vec2(); m_direction = new b2Vec2(); m_cornerDir1 = new b2Vec2(); m_cornerDir2 = new b2Vec2(); super(def); m_type = e_edgeShape; m_prevEdge = null; m_nextEdge = null; m_v1 = v1; m_v2 = v2; m_direction.Set((m_v2.x - m_v1.x), (m_v2.y - m_v1.y)); m_length = m_direction.Normalize(); m_normal.Set(m_direction.y, -(m_direction.x)); m_coreV1.Set(((-(b2Settings.b2_toiSlop) * (m_normal.x - m_direction.x)) + m_v1.x), ((-(b2Settings.b2_toiSlop) * (m_normal.y - m_direction.y)) + m_v1.y)); m_coreV2.Set(((-(b2Settings.b2_toiSlop) * (m_normal.x + m_direction.x)) + m_v2.x), ((-(b2Settings.b2_toiSlop) * (m_normal.y + m_direction.y)) + m_v2.y)); m_cornerDir1 = m_normal; m_cornerDir2.Set(-(m_normal.x), -(m_normal.y)); } b2internal function SetPrevEdge(edge:b2EdgeShape, core:b2Vec2, cornerDir:b2Vec2, convex:Boolean):void{ m_prevEdge = edge; m_coreV1 = core; m_cornerDir1 = cornerDir; m_cornerConvex1 = convex; } public function GetCorner2Vector():b2Vec2{ return (m_cornerDir2); } public function GetDirectionVector():b2Vec2{ return (m_direction); } override public function ComputeAABB(aabb:b2AABB, transform:b2XForm):void{ var tMat:b2Mat22 = transform.R; var v1X:Number = (transform.position.x + ((tMat.col1.x * m_v1.x) + (tMat.col2.x * m_v1.y))); var v1Y:Number = (transform.position.y + ((tMat.col1.y * m_v1.x) + (tMat.col2.y * m_v1.y))); var v2X:Number = (transform.position.x + ((tMat.col1.x * m_v2.x) + (tMat.col2.x * m_v2.y))); var v2Y:Number = (transform.position.y + ((tMat.col1.y * m_v2.x) + (tMat.col2.y * m_v2.y))); if (v1X < v2X){ aabb.lowerBound.x = v1X; aabb.upperBound.x = v2X; } else { aabb.lowerBound.x = v2X; aabb.upperBound.x = v1X; }; if (v1Y < v2Y){ aabb.lowerBound.y = v1Y; aabb.upperBound.y = v2Y; } else { aabb.lowerBound.y = v2Y; aabb.upperBound.y = v1Y; }; } override public function TestSegment(transform:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ var tMat:b2Mat22; var nY:Number; var bX:Number; var bY:Number; var a:Number; var mu2:Number; var nLen:Number; var rX:Number = (segment.p2.x - segment.p1.x); var rY:Number = (segment.p2.y - segment.p1.y); tMat = transform.R; var v1X:Number = (transform.position.x + ((tMat.col1.x * m_v1.x) + (tMat.col2.x * m_v1.y))); var v1Y:Number = (transform.position.y + ((tMat.col1.y * m_v1.x) + (tMat.col2.y * m_v1.y))); var nX:Number = ((transform.position.y + ((tMat.col1.y * m_v2.x) + (tMat.col2.y * m_v2.y))) - v1Y); nY = -(((transform.position.x + ((tMat.col1.x * m_v2.x) + (tMat.col2.x * m_v2.y))) - v1X)); var k_slop:Number = (100 * Number.MIN_VALUE); var denom:Number = -(((rX * nX) + (rY * nY))); if (denom > k_slop){ bX = (segment.p1.x - v1X); bY = (segment.p1.y - v1Y); a = ((bX * nX) + (bY * nY)); if ((((0 <= a)) && ((a <= (maxLambda * denom))))){ mu2 = ((-(rX) * bY) + (rY * bX)); if (((((-(k_slop) * denom) <= mu2)) && ((mu2 <= (denom * (1 + k_slop)))))){ a = (a / denom); lambda[0] = a; nLen = Math.sqrt(((nX * nX) + (nY * nY))); normal.x = (nX / nLen); normal.y = (nY / nLen); return (e_hitCollide); }; }; }; return (e_missCollide); } public function GetNextEdge():b2EdgeShape{ return (m_nextEdge); } override public function ComputeMass(massData:b2MassData):void{ massData.mass = 0; massData.center.SetV(m_v1); massData.I = 0; } public function Corner1IsConvex():Boolean{ return (m_cornerConvex1); } public function Corner2IsConvex():Boolean{ return (m_cornerConvex2); } public function Support(xf:b2XForm, dX:Number, dY:Number):b2Vec2{ var tMat:b2Mat22 = xf.R; var v1X:Number = (xf.position.x + ((tMat.col1.x * m_coreV1.x) + (tMat.col2.x * m_coreV1.y))); var v1Y:Number = (xf.position.y + ((tMat.col1.y * m_coreV1.x) + (tMat.col2.y * m_coreV1.y))); var v2X:Number = (xf.position.x + ((tMat.col1.x * m_coreV2.x) + (tMat.col2.x * m_coreV2.y))); var v2Y:Number = (xf.position.y + ((tMat.col1.y * m_coreV2.x) + (tMat.col2.y * m_coreV2.y))); if (((v1X * dX) + (v1Y * dY)) > ((v2X * dX) + (v2Y * dY))){ s_supportVec.x = v1X; s_supportVec.y = v1Y; } else { s_supportVec.x = v2X; s_supportVec.y = v2Y; }; return (s_supportVec); } b2internal function SetNextEdge(edge:b2EdgeShape, core:b2Vec2, cornerDir:b2Vec2, convex:Boolean):void{ m_nextEdge = edge; m_coreV2 = core; m_cornerDir2 = cornerDir; m_cornerConvex2 = convex; } public function GetLength():Number{ return (m_length); } override public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ var v0:b2Vec2 = new b2Vec2((normal.x * offset), (normal.y * offset)); var v1:b2Vec2 = b2Math.b2MulX(xf, m_v1); var v2:b2Vec2 = b2Math.b2MulX(xf, m_v2); var d1:Number = (b2Math.b2Dot(normal, v1) - offset); var d2:Number = (b2Math.b2Dot(normal, v2) - offset); if (d1 > 0){ if (d2 > 0){ return (0); }; v1.x = (((-(d2) / (d1 - d2)) * v1.x) + ((d1 / (d1 - d2)) * v2.x)); v1.y = (((-(d2) / (d1 - d2)) * v1.y) + ((d1 / (d1 - d2)) * v2.y)); } else { if (d2 > 0){ v2.x = (((-(d2) / (d1 - d2)) * v1.x) + ((d1 / (d1 - d2)) * v2.x)); v2.y = (((-(d2) / (d1 - d2)) * v1.y) + ((d1 / (d1 - d2)) * v2.y)); }; }; c.x = (((v0.x + v1.x) + v2.x) / 3); c.y = (((v0.y + v1.y) + v2.y) / 3); return ((0.5 * (((v1.x - v0.x) * (v2.y - v0.y)) - ((v1.y - v0.y) * (v2.x - v0.x))))); } public function GetCorner1Vector():b2Vec2{ return (m_cornerDir1); } override public function ComputeSweptAABB(aabb:b2AABB, transform1:b2XForm, transform2:b2XForm):void{ var tMat:b2Mat22; tMat = transform1.R; var v1X:Number = (transform1.position.x + ((tMat.col1.x * m_v1.x) + (tMat.col2.x * m_v1.y))); var v1Y:Number = (transform1.position.y + ((tMat.col1.y * m_v1.x) + (tMat.col2.y * m_v1.y))); var v2X:Number = (transform1.position.x + ((tMat.col1.x * m_v2.x) + (tMat.col2.x * m_v2.y))); var v2Y:Number = (transform1.position.y + ((tMat.col1.y * m_v2.x) + (tMat.col2.y * m_v2.y))); tMat = transform2.R; var v3X:Number = (transform2.position.x + ((tMat.col1.x * m_v1.x) + (tMat.col2.x * m_v1.y))); var v3Y:Number = (transform2.position.y + ((tMat.col1.y * m_v1.x) + (tMat.col2.y * m_v1.y))); var v4X:Number = (transform2.position.x + ((tMat.col1.x * m_v2.x) + (tMat.col2.x * m_v2.y))); var v4Y:Number = (transform2.position.y + ((tMat.col1.y * m_v2.x) + (tMat.col2.y * m_v2.y))); aabb.lowerBound.x = ((((((v1X < v2X)) ? v1X : v2X < v3X)) ? ((v1X < v2X)) ? v1X : v2X : v3X < v4X)) ? ((((v1X < v2X)) ? v1X : v2X < v3X)) ? ((v1X < v2X)) ? v1X : v2X : v3X : v4X; aabb.lowerBound.y = ((((((v1Y < v2Y)) ? v1Y : v2Y < v3Y)) ? ((v1Y < v2Y)) ? v1Y : v2Y : v3Y < v4Y)) ? ((((v1Y < v2Y)) ? v1Y : v2Y < v3Y)) ? ((v1Y < v2Y)) ? v1Y : v2Y : v3Y : v4Y; aabb.upperBound.x = ((((((v1X > v2X)) ? v1X : v2X > v3X)) ? ((v1X > v2X)) ? v1X : v2X : v3X > v4X)) ? ((((v1X > v2X)) ? v1X : v2X > v3X)) ? ((v1X > v2X)) ? v1X : v2X : v3X : v4X; aabb.upperBound.y = ((((((v1Y > v2Y)) ? v1Y : v2Y > v3Y)) ? ((v1Y > v2Y)) ? v1Y : v2Y : v3Y > v4Y)) ? ((((v1Y > v2Y)) ? v1Y : v2Y > v3Y)) ? ((v1Y > v2Y)) ? v1Y : v2Y : v3Y : v4Y; } public function GetCoreVertex1():b2Vec2{ return (m_coreV1); } public function GetCoreVertex2():b2Vec2{ return (m_coreV2); } public function GetFirstVertex(xf:b2XForm):b2Vec2{ var tMat:b2Mat22 = xf.R; return (new b2Vec2((xf.position.x + ((tMat.col1.x * m_coreV1.x) + (tMat.col2.x * m_coreV1.y))), (xf.position.y + ((tMat.col1.y * m_coreV1.x) + (tMat.col2.y * m_coreV1.y))))); } public function GetNormalVector():b2Vec2{ return (m_normal); } public function GetPrevEdge():b2EdgeShape{ return (m_prevEdge); } override b2internal function UpdateSweepRadius(center:b2Vec2):void{ var dX:Number = (m_coreV1.x - center.x); var dY:Number = (m_coreV1.y - center.y); var d1:Number = ((dX * dX) + (dY * dY)); dX = (m_coreV2.x - center.x); dY = (m_coreV2.y - center.y); var d2:Number = ((dX * dX) + (dY * dY)); m_sweepRadius = Math.sqrt(((d1 > d2)) ? d1 : d2); } public function GetVertex1():b2Vec2{ return (m_v1); } public function GetVertex2():b2Vec2{ return (m_v2); } override public function TestPoint(transform:b2XForm, p:b2Vec2):Boolean{ return (false); } } }//package Box2D.Collision.Shapes
Section 5
//b2FilterData (Box2D.Collision.Shapes.b2FilterData) package Box2D.Collision.Shapes { public class b2FilterData { public var maskBits:uint;// = 0xFFFF public var groupIndex:int;// = 0 public var categoryBits:uint;// = 1 public function b2FilterData(){ super(); } public function Copy():b2FilterData{ var copy:b2FilterData = new b2FilterData(); copy.categoryBits = categoryBits; copy.maskBits = maskBits; copy.groupIndex = groupIndex; return (copy); } } }//package Box2D.Collision.Shapes
Section 6
//b2MassData (Box2D.Collision.Shapes.b2MassData) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; public class b2MassData { public var mass:Number;// = 0 public var center:b2Vec2; public var I:Number;// = 0 public function b2MassData(){ center = new b2Vec2(0, 0); super(); } } }//package Box2D.Collision.Shapes
Section 7
//b2PolygonDef (Box2D.Collision.Shapes.b2PolygonDef) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PolygonDef extends b2ShapeDef { public var vertices:Array; public var vertexCount:int; private static var s_mat:b2Mat22 = new b2Mat22(); public function b2PolygonDef(){ vertices = new Array(b2Settings.b2_maxPolygonVertices); super(); type = b2Shape.e_polygonShape; vertexCount = 0; var i:int; while (i < b2Settings.b2_maxPolygonVertices) { vertices[i] = new b2Vec2(); i++; }; } public function SetAsOrientedBox(hx:Number, hy:Number, center:b2Vec2=null, angle:Number=0):void{ var xfPosition:b2Vec2; var xfR:b2Mat22; var i:int; vertexCount = 4; vertices[0].Set(-(hx), -(hy)); vertices[1].Set(hx, -(hy)); vertices[2].Set(hx, hy); vertices[3].Set(-(hx), hy); if (center){ xfPosition = center; xfR = s_mat; xfR.Set(angle); i = 0; while (i < vertexCount) { center = vertices[i]; hx = (xfPosition.x + ((xfR.col1.x * center.x) + (xfR.col2.x * center.y))); center.y = (xfPosition.y + ((xfR.col1.y * center.x) + (xfR.col2.y * center.y))); center.x = hx; i++; }; }; } public function SetAsBox(hx:Number, hy:Number):void{ vertexCount = 4; vertices[0].Set(-(hx), -(hy)); vertices[1].Set(hx, -(hy)); vertices[2].Set(hx, hy); vertices[3].Set(-(hx), hy); } } }//package Box2D.Collision.Shapes
Section 8
//b2PolygonShape (Box2D.Collision.Shapes.b2PolygonShape) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2PolygonShape extends b2Shape { private var m_coreVertices:Array; b2internal var m_vertices:Array; private var s_supportVec:b2Vec2; b2internal var m_centroid:b2Vec2; b2internal var m_normals:Array; private var m_obb:b2OBB; b2internal var m_vertexCount:int; private static var s_computeMat:b2Mat22 = new b2Mat22(); private static var s_sweptAABB1:b2AABB = new b2AABB(); private static var s_sweptAABB2:b2AABB = new b2AABB(); public function b2PolygonShape(def:b2ShapeDef){ var i:int; var edgeX:Number; var edgeY:Number; var len:Number; var n1X:Number; var n1Y:Number; var n2X:Number; var n2Y:Number; var vX:Number; var vY:Number; var dX:Number; var dY:Number; var det:Number; s_supportVec = new b2Vec2(); m_obb = new b2OBB(); m_vertices = new Array(b2Settings.b2_maxPolygonVertices); m_normals = new Array(b2Settings.b2_maxPolygonVertices); m_coreVertices = new Array(b2Settings.b2_maxPolygonVertices); super(def); m_type = e_polygonShape; var poly:b2PolygonDef = (def as b2PolygonDef); m_vertexCount = poly.vertexCount; var i1:int = i; var i2:int = i; i = 0; while (i < m_vertexCount) { m_vertices[i] = poly.vertices[i].Copy(); i++; }; i = 0; while (i < m_vertexCount) { i1 = i; i2 = (((i + 1) < m_vertexCount)) ? (i + 1) : 0; edgeX = (m_vertices[i2].x - m_vertices[i1].x); edgeY = (m_vertices[i2].y - m_vertices[i1].y); len = Math.sqrt(((edgeX * edgeX) + (edgeY * edgeY))); m_normals[i] = new b2Vec2((edgeY / len), (-(edgeX) / len)); i++; }; m_centroid = ComputeCentroid(poly.vertices, poly.vertexCount); ComputeOBB(m_obb, m_vertices, m_vertexCount); i = 0; while (i < m_vertexCount) { i1 = (((i - 1) >= 0)) ? (i - 1) : (m_vertexCount - 1); i2 = i; n1X = m_normals[i1].x; n1Y = m_normals[i1].y; n2X = m_normals[i2].x; n2Y = m_normals[i2].y; vX = (m_vertices[i].x - m_centroid.x); vY = (m_vertices[i].y - m_centroid.y); dX = (((n1X * vX) + (n1Y * vY)) - b2Settings.b2_toiSlop); dY = (((n2X * vX) + (n2Y * vY)) - b2Settings.b2_toiSlop); det = (1 / ((n1X * n2Y) - (n1Y * n2X))); m_coreVertices[i] = new b2Vec2(((det * ((n2Y * dX) - (n1Y * dY))) + m_centroid.x), ((det * ((n1X * dY) - (n2X * dX))) + m_centroid.y)); i++; }; } override public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ var i:int; var p3:b2Vec2; var isSubmerged:Boolean; var md:b2MassData; var triangleArea:Number; var normalL:b2Vec2 = b2Math.b2MulTMV(xf.R, normal); var offsetL:Number = (offset - b2Math.b2Dot(normal, xf.position)); var depths:Array = new Array(); var diveCount:int; var intoIndex = -1; var outoIndex = -1; var lastSubmerged:Boolean; i = 0; while (i < m_vertexCount) { depths[i] = (b2Math.b2Dot(normalL, m_vertices[i]) - offsetL); isSubmerged = (depths[i] < -(Number.MIN_VALUE)); if (i > 0){ if (isSubmerged){ if (!lastSubmerged){ intoIndex = (i - 1); diveCount++; }; } else { if (lastSubmerged){ outoIndex = (i - 1); diveCount++; }; }; }; lastSubmerged = isSubmerged; i++; }; switch (diveCount){ case 0: if (lastSubmerged){ md = new b2MassData(); ComputeMass(md); c.SetV(b2Math.b2MulX(xf, md.center)); return ((md.mass / m_density)); }; return (0); case 1: if (intoIndex == -1){ intoIndex = (m_vertexCount - 1); } else { outoIndex = (m_vertexCount - 1); }; break; }; var intoIndex2:int = ((intoIndex + 1) % m_vertexCount); var outoIndex2:int = ((outoIndex + 1) % m_vertexCount); var intoLamdda:Number = ((0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex])); var outoLamdda:Number = ((0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex])); var intoVec:b2Vec2 = new b2Vec2(((m_vertices[intoIndex].x * (1 - intoLamdda)) + (m_vertices[intoIndex2].x * intoLamdda)), ((m_vertices[intoIndex].y * (1 - intoLamdda)) + (m_vertices[intoIndex2].y * intoLamdda))); var outoVec:b2Vec2 = new b2Vec2(((m_vertices[outoIndex].x * (1 - outoLamdda)) + (m_vertices[outoIndex2].x * outoLamdda)), ((m_vertices[outoIndex].y * (1 - outoLamdda)) + (m_vertices[outoIndex2].y * outoLamdda))); var area:Number = 0; var center:b2Vec2 = new b2Vec2(); var p2:b2Vec2 = m_vertices[intoIndex2]; i = intoIndex2; while (i != outoIndex2) { i = ((i + 1) % m_vertexCount); if (i == outoIndex2){ p3 = outoVec; } else { p3 = m_vertices[i]; }; triangleArea = (0.5 * (((p2.x - intoVec.x) * (p3.y - intoVec.y)) - ((p2.y - intoVec.y) * (p3.x - intoVec.x)))); area = (area + triangleArea); center.x = (center.x + ((triangleArea * ((intoVec.x + p2.x) + p3.x)) / 3)); center.y = (center.y + ((triangleArea * ((intoVec.y + p2.y) + p3.y)) / 3)); p2 = p3; }; center.Multiply((1 / area)); c.SetV(b2Math.b2MulX(xf, center)); return (area); } override public function ComputeSweptAABB(aabb:b2AABB, transform1:b2XForm, transform2:b2XForm):void{ var aabb1:b2AABB = s_sweptAABB1; var aabb2:b2AABB = s_sweptAABB2; ComputeAABB(aabb1, transform1); ComputeAABB(aabb2, transform2); aabb.lowerBound.Set(((aabb1.lowerBound.x < aabb2.lowerBound.x)) ? aabb1.lowerBound.x : aabb2.lowerBound.x, ((aabb1.lowerBound.y < aabb2.lowerBound.y)) ? aabb1.lowerBound.y : aabb2.lowerBound.y); aabb.upperBound.Set(((aabb1.upperBound.x > aabb2.upperBound.x)) ? aabb1.upperBound.x : aabb2.upperBound.x, ((aabb1.upperBound.y > aabb2.upperBound.y)) ? aabb1.upperBound.y : aabb2.upperBound.y); } public function GetVertices():Array{ return (m_vertices); } public function GetCoreVertices():Array{ return (m_coreVertices); } public function GetCentroid():b2Vec2{ return (m_centroid); } public function GetOBB():b2OBB{ return (m_obb); } public function GetFirstVertex(xf:b2XForm):b2Vec2{ return (b2Math.b2MulX(xf, m_coreVertices[0])); } public function Centroid(xf:b2XForm):b2Vec2{ return (b2Math.b2MulX(xf, m_centroid)); } override public function TestSegment(xf:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ var tX:Number; var tY:Number; var tMat:b2Mat22; var tVec:b2Vec2; var numerator:Number; var denominator:Number; var lower:Number = 0; var upper:Number = maxLambda; tX = (segment.p1.x - xf.position.x); tY = (segment.p1.y - xf.position.y); tMat = xf.R; var p1X:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var p1Y:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tX = (segment.p2.x - xf.position.x); tY = (segment.p2.y - xf.position.y); tMat = xf.R; var p2X:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var p2Y:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var index = -1; var i:int; while (i < m_vertexCount) { tVec = m_vertices[i]; tX = (tVec.x - p1X); tY = (tVec.y - p1Y); tVec = m_normals[i]; numerator = ((tVec.x * tX) + (tVec.y * tY)); denominator = ((tVec.x * dX) + (tVec.y * dY)); if (denominator == 0){ if (numerator < 0){ return (e_missCollide); }; } else { if ((((denominator < 0)) && ((numerator < (lower * denominator))))){ lower = (numerator / denominator); index = i; } else { if ((((denominator > 0)) && ((numerator < (upper * denominator))))){ upper = (numerator / denominator); }; }; }; if (upper < lower){ return (e_missCollide); }; i++; }; if (index >= 0){ lambda[0] = lower; tMat = xf.R; tVec = m_normals[index]; normal.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); normal.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); return (e_hitCollide); }; lambda[0] = 0; return (e_startsInsideCollide); } override public function ComputeMass(massData:b2MassData):void{ var p2:b2Vec2; var p3:b2Vec2; var e1X:Number; var e1Y:Number; var e2X:Number; var e2Y:Number; var D:Number; var triangleArea:Number; var px:Number; var py:Number; var ex1:Number; var ey1:Number; var ex2:Number; var ey2:Number; var intx2:Number; var inty2:Number; var centerX:Number = 0; var centerY:Number = 0; var area:Number = 0; var I:Number = 0; var p1X:Number = 0; var p1Y:Number = 0; var k_inv3:Number = (1 / 3); var i:int; while (i < m_vertexCount) { p2 = m_vertices[i]; p3 = (((i + 1) < m_vertexCount)) ? m_vertices[int((i + 1))] : m_vertices[0]; e1X = (p2.x - p1X); e1Y = (p2.y - p1Y); e2X = (p3.x - p1X); e2Y = (p3.y - p1Y); D = ((e1X * e2Y) - (e1Y * e2X)); triangleArea = (0.5 * D); area = (area + triangleArea); centerX = (centerX + ((triangleArea * k_inv3) * ((p1X + p2.x) + p3.x))); centerY = (centerY + ((triangleArea * k_inv3) * ((p1Y + p2.y) + p3.y))); px = p1X; py = p1Y; ex1 = e1X; ey1 = e1Y; ex2 = e2X; ey2 = e2Y; intx2 = ((k_inv3 * ((0.25 * (((ex1 * ex1) + (ex2 * ex1)) + (ex2 * ex2))) + ((px * ex1) + (px * ex2)))) + ((0.5 * px) * px)); inty2 = ((k_inv3 * ((0.25 * (((ey1 * ey1) + (ey2 * ey1)) + (ey2 * ey2))) + ((py * ey1) + (py * ey2)))) + ((0.5 * py) * py)); I = (I + (D * (intx2 + inty2))); i++; }; massData.mass = (m_density * area); centerX = (centerX * (1 / area)); centerY = (centerY * (1 / area)); massData.center.Set(centerX, centerY); massData.I = (m_density * I); } public function GetNormals():Array{ return (m_normals); } public function Support(xf:b2XForm, dX:Number, dY:Number):b2Vec2{ var tVec:b2Vec2; var tMat:b2Mat22; var value:Number; tMat = xf.R; var dLocalX:Number = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); var dLocalY:Number = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); var bestIndex:int; tVec = m_coreVertices[0]; var bestValue:Number = ((tVec.x * dLocalX) + (tVec.y * dLocalY)); var i = 1; while (i < m_vertexCount) { tVec = m_coreVertices[i]; value = ((tVec.x * dLocalX) + (tVec.y * dLocalY)); if (value > bestValue){ bestIndex = i; bestValue = value; }; i++; }; tMat = xf.R; tVec = m_coreVertices[bestIndex]; s_supportVec.x = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); s_supportVec.y = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); return (s_supportVec); } public function GetVertexCount():int{ return (m_vertexCount); } override public function ComputeAABB(aabb:b2AABB, xf:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var R:b2Mat22 = s_computeMat; tMat = xf.R; tVec = m_obb.R.col1; R.col1.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); R.col1.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tVec = m_obb.R.col2; R.col2.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); R.col2.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); R.Abs(); var absR:b2Mat22 = R; tVec = m_obb.extents; var hX:Number = ((absR.col1.x * tVec.x) + (absR.col2.x * tVec.y)); var hY:Number = ((absR.col1.y * tVec.x) + (absR.col2.y * tVec.y)); tMat = xf.R; tVec = m_obb.center; var positionX:Number = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var positionY:Number = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); aabb.lowerBound.Set((positionX - hX), (positionY - hY)); aabb.upperBound.Set((positionX + hX), (positionY + hY)); } override b2internal function UpdateSweepRadius(center:b2Vec2):void{ var tVec:b2Vec2; var dX:Number; var dY:Number; m_sweepRadius = 0; var i:int; while (i < m_vertexCount) { tVec = m_coreVertices[i]; dX = (tVec.x - center.x); dY = (tVec.y - center.y); dX = Math.sqrt(((dX * dX) + (dY * dY))); if (dX > m_sweepRadius){ m_sweepRadius = dX; }; i++; }; } override public function TestPoint(xf:b2XForm, p:b2Vec2):Boolean{ var tVec:b2Vec2; var dot:Number; var tMat:b2Mat22 = xf.R; var tX:Number = (p.x - xf.position.x); var tY:Number = (p.y - xf.position.y); var pLocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var pLocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var i:int; while (i < m_vertexCount) { tVec = m_vertices[i]; tX = (pLocalX - tVec.x); tY = (pLocalY - tVec.y); tVec = m_normals[i]; dot = ((tVec.x * tX) + (tVec.y * tY)); if (dot > 0){ return (false); }; i++; }; return (true); } public static function ComputeCentroid(vs:Array, count:int):b2Vec2{ var c:b2Vec2; var inv3:Number; var p2:b2Vec2; var p3:b2Vec2; var e1X:Number; var e1Y:Number; var e2X:Number; var e2Y:Number; var D:Number; var triangleArea:Number; c = new b2Vec2(); var area:Number = 0; var p1X:Number = 0; var p1Y:Number = 0; inv3 = (1 / 3); var i:int; while (i < count) { p2 = vs[i]; p3 = (((i + 1) < count)) ? vs[int((i + 1))] : vs[0]; e1X = (p2.x - p1X); e1Y = (p2.y - p1Y); e2X = (p3.x - p1X); e2Y = (p3.y - p1Y); D = ((e1X * e2Y) - (e1Y * e2X)); triangleArea = (0.5 * D); area = (area + triangleArea); c.x = (c.x + ((triangleArea * inv3) * ((p1X + p2.x) + p3.x))); c.y = (c.y + ((triangleArea * inv3) * ((p1Y + p2.y) + p3.y))); i++; }; c.x = (c.x * (1 / area)); c.y = (c.y * (1 / area)); return (c); } b2internal static function ComputeOBB(obb:b2OBB, vs:Array, count:int):void{ var i:int; var root:b2Vec2; var uxX:Number; var uxY:Number; var length:Number; var uyX:Number; var uyY:Number; var lowerX:Number; var lowerY:Number; var upperX:Number; var upperY:Number; var j:int; var area:Number; var dX:Number; var dY:Number; var rX:Number; var rY:Number; var centerX:Number; var centerY:Number; var tMat:b2Mat22; var p:Array = new Array((b2Settings.b2_maxPolygonVertices + 1)); i = 0; while (i < count) { p[i] = vs[i]; i++; }; p[count] = p[0]; var minArea:Number = Number.MAX_VALUE; i = 1; while (i <= count) { root = p[int((i - 1))]; uxX = (p[i].x - root.x); uxY = (p[i].y - root.y); length = Math.sqrt(((uxX * uxX) + (uxY * uxY))); uxX = (uxX / length); uxY = (uxY / length); uyX = -(uxY); uyY = uxX; lowerX = Number.MAX_VALUE; lowerY = Number.MAX_VALUE; upperX = -(Number.MAX_VALUE); upperY = -(Number.MAX_VALUE); j = 0; while (j < count) { dX = (p[j].x - root.x); dY = (p[j].y - root.y); rX = ((uxX * dX) + (uxY * dY)); rY = ((uyX * dX) + (uyY * dY)); if (rX < lowerX){ lowerX = rX; }; if (rY < lowerY){ lowerY = rY; }; if (rX > upperX){ upperX = rX; }; if (rY > upperY){ upperY = rY; }; j++; }; area = ((upperX - lowerX) * (upperY - lowerY)); if (area < (0.95 * minArea)){ minArea = area; obb.R.col1.x = uxX; obb.R.col1.y = uxY; obb.R.col2.x = uyX; obb.R.col2.y = uyY; centerX = (0.5 * (lowerX + upperX)); centerY = (0.5 * (lowerY + upperY)); tMat = obb.R; obb.center.x = (root.x + ((tMat.col1.x * centerX) + (tMat.col2.x * centerY))); obb.center.y = (root.y + ((tMat.col1.y * centerX) + (tMat.col2.y * centerY))); obb.extents.x = (0.5 * (upperX - lowerX)); obb.extents.y = (0.5 * (upperY - lowerY)); }; i++; }; } } }//package Box2D.Collision.Shapes
Section 9
//b2Shape (Box2D.Collision.Shapes.b2Shape) package Box2D.Collision.Shapes { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2Shape { b2internal var m_next:b2Shape; b2internal var m_type:int; b2internal var m_sweepRadius:Number; b2internal var m_density:Number; private var m_filter:b2FilterData; b2internal var m_friction:Number; private var m_isSensor:Boolean; b2internal var m_restitution:Number; private var m_proxy:b2Proxy; private var m_userData; b2internal var m_body:b2Body; b2internal static const e_polygonShape:int = 1; public static const e_hitCollide:int = 1; public static const e_missCollide:int = 0; b2internal static const e_edgeShape:int = 2; b2internal static const e_unknownShape:int = -1; b2internal static const e_circleShape:int = 0; b2internal static const e_shapeTypeCount:int = 3; public static const e_startsInsideCollide:int = -1; private static var s_resetAABB:b2AABB = new b2AABB(); private static var s_syncAABB:b2AABB = new b2AABB(); private static var s_proxyAABB:b2AABB = new b2AABB(); public function b2Shape(def:b2ShapeDef){ super(); m_userData = def.userData; m_friction = def.friction; m_restitution = def.restitution; m_density = def.density; m_body = null; m_sweepRadius = 0; m_next = null; m_proxy = null; m_filter = def.filter.Copy(); m_isSensor = def.isSensor; } public function ComputeSubmergedArea(normal:b2Vec2, offset:Number, xf:b2XForm, c:b2Vec2):Number{ return (0); } public function SetUserData(data):void{ m_userData = data; } public function GetSweepRadius():Number{ return (m_sweepRadius); } public function GetNext():b2Shape{ return (m_next); } public function ComputeSweptAABB(aabb:b2AABB, xf1:b2XForm, xf2:b2XForm):void{ } public function SetRestitution(restitution:Number):void{ m_restitution = restitution; } public function GetType():int{ return (m_type); } public function GetRestitution():Number{ return (m_restitution); } public function SetSensor(sensor:Boolean):void{ m_isSensor = sensor; } public function GetFriction():Number{ return (m_friction); } public function GetFilterData():b2FilterData{ return (m_filter.Copy()); } public function SetFriction(friction:Number):void{ m_friction = friction; } public function TestSegment(xf:b2XForm, lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):int{ return (e_missCollide); } b2internal function RefilterProxy(broadPhase:b2BroadPhase, transform:b2XForm):void{ if (m_proxy == null){ return; }; broadPhase.DestroyProxy(m_proxy); var aabb:b2AABB = s_resetAABB; ComputeAABB(aabb, transform); var inRange:Boolean = broadPhase.InRange(aabb); if (inRange){ m_proxy = broadPhase.CreateProxy(aabb, this); } else { m_proxy = null; }; } public function IsSensor():Boolean{ return (m_isSensor); } public function GetUserData(){ return (m_userData); } b2internal function Synchronize(broadPhase:b2BroadPhase, transform1:b2XForm, transform2:b2XForm):Boolean{ if (m_proxy == null){ return (false); }; var aabb:b2AABB = s_syncAABB; ComputeSweptAABB(aabb, transform1, transform2); if (broadPhase.InRange(aabb)){ broadPhase.MoveProxy(m_proxy, aabb); return (true); }; return (false); } public function ComputeMass(massData:b2MassData):void{ } public function SetFilterData(filter:b2FilterData):void{ m_filter = filter.Copy(); } b2internal function DestroyProxy(broadPhase:b2BroadPhase):void{ if (m_proxy){ broadPhase.DestroyProxy(m_proxy); m_proxy = null; }; } b2internal function UpdateSweepRadius(center:b2Vec2):void{ } public function ComputeAABB(aabb:b2AABB, xf:b2XForm):void{ } public function GetBody():b2Body{ return (m_body); } b2internal function CreateProxy(broadPhase:b2BroadPhase, transform:b2XForm):void{ var aabb:b2AABB = s_proxyAABB; ComputeAABB(aabb, transform); var inRange:Boolean = broadPhase.InRange(aabb); if (inRange){ m_proxy = broadPhase.CreateProxy(aabb, this); } else { m_proxy = null; }; } public function TestPoint(xf:b2XForm, p:b2Vec2):Boolean{ return (false); } b2internal static function Destroy(shape:b2Shape, allocator):void{ var _local3:b2EdgeShape; switch (shape.m_type){ case e_edgeShape: _local3 = (shape as b2EdgeShape); if (_local3.m_nextEdge != null){ _local3.m_nextEdge.m_prevEdge = null; }; if (_local3.m_prevEdge != null){ _local3.m_prevEdge.m_nextEdge = null; }; break; }; } b2internal static function Create(def:b2ShapeDef, allocator):b2Shape{ switch (def.type){ case e_circleShape: return (new b2CircleShape(def)); case e_polygonShape: return (new b2PolygonShape(def)); default: return (null); }; } } }//package Box2D.Collision.Shapes
Section 10
//b2ShapeDef (Box2D.Collision.Shapes.b2ShapeDef) package Box2D.Collision.Shapes { public class b2ShapeDef { public var friction:Number;// = 0.2 public var isSensor:Boolean;// = false public var density:Number;// = 0 public var restitution:Number;// = 0 public var userData;// = null public var filter:b2FilterData; public var type:int;// = -1 public function b2ShapeDef(){ filter = new b2FilterData(); super(); } } }//package Box2D.Collision.Shapes
Section 11
//b2AABB (Box2D.Collision.b2AABB) package Box2D.Collision { import Box2D.Common.Math.*; public class b2AABB { public var upperBound:b2Vec2; public var lowerBound:b2Vec2; public function b2AABB(){ lowerBound = new b2Vec2(); upperBound = new b2Vec2(); super(); } public function IsValid():Boolean{ var dX:Number = (upperBound.x - lowerBound.x); var dY:Number = (upperBound.y - lowerBound.y); var valid:Boolean = (((dX >= 0)) && ((dY >= 0))); valid = ((((valid) && (lowerBound.IsValid()))) && (upperBound.IsValid())); return (valid); } } }//package Box2D.Collision
Section 12
//b2Bound (Box2D.Collision.b2Bound) package Box2D.Collision { public class b2Bound { public var value:uint; public var stabbingCount:uint; public var proxy:b2Proxy; public function b2Bound(){ super(); } public function Swap(b:b2Bound):void{ var tempValue:uint = value; var tempProxy:b2Proxy = proxy; var tempStabbingCount:uint = stabbingCount; value = b.value; proxy = b.proxy; stabbingCount = b.stabbingCount; b.value = tempValue; b.proxy = tempProxy; b.stabbingCount = tempStabbingCount; } public function IsLower():Boolean{ return (((value & 1) == 0)); } public function IsUpper():Boolean{ return (((value & 1) == 1)); } } }//package Box2D.Collision
Section 13
//b2BoundValues (Box2D.Collision.b2BoundValues) package Box2D.Collision { public class b2BoundValues { public var lowerValues:Array; public var upperValues:Array; public function b2BoundValues(){ lowerValues = [0, 0]; upperValues = [0, 0]; super(); } } }//package Box2D.Collision
Section 14
//b2BroadPhase (Box2D.Collision.b2BroadPhase) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2BroadPhase { b2internal var m_bounds:Array; b2internal var m_quantizationFactor:b2Vec2; b2internal var m_worldAABB:b2AABB; private var m_querySortKeys:Array; private var m_freeProxy:b2Proxy; b2internal var m_proxyCount:int; b2internal var m_proxyPool:Array; private var m_queryResultCount:int; b2internal var m_pairManager:b2PairManager; private var m_timeStamp:uint; private var m_queryResults:Array; public static const b2_nullEdge:uint = 0xFFFF; public static const b2_invalid:uint = 0xFFFF; public static var s_validate:Boolean = false; public function b2BroadPhase(worldAABB:b2AABB, callback:b2PairCallback){ var i:int; m_pairManager = new b2PairManager(); m_proxyPool = new Array(); m_bounds = new Array(); m_querySortKeys = new Array(); m_queryResults = new Array(); m_quantizationFactor = new b2Vec2(); super(); m_pairManager.Initialize(this, callback); m_worldAABB = worldAABB; m_proxyCount = 0; m_bounds = new Array(2); i = 0; while (i < 2) { m_bounds[i] = new Array(); i++; }; var dX:Number = (worldAABB.upperBound.x - worldAABB.lowerBound.x); var dY:Number = (worldAABB.upperBound.y - worldAABB.lowerBound.y); m_quantizationFactor.x = (b2Settings.USHRT_MAX / dX); m_quantizationFactor.y = (b2Settings.USHRT_MAX / dY); m_timeStamp = 1; m_queryResultCount = 0; } public function QueryAABB(aabb:b2AABB, userData, maxCount:int):int{ var lowerIndex:uint; var upperIndex:uint; var proxy:b2Proxy; var lowerValues:Array = new Array(); var upperValues:Array = new Array(); ComputeBounds(lowerValues, upperValues, aabb); var lowerIndexOut:Array = [lowerIndex]; var upperIndexOut:Array = [upperIndex]; Query(lowerIndexOut, upperIndexOut, lowerValues[0], upperValues[0], m_bounds[0], (2 * m_proxyCount), 0); Query(lowerIndexOut, upperIndexOut, lowerValues[1], upperValues[1], m_bounds[1], (2 * m_proxyCount), 1); var count:int; var i:int; while ((((i < m_queryResultCount)) && ((count < maxCount)))) { proxy = m_queryResults[i]; userData[i] = proxy.userData; i++; count++; }; m_queryResultCount = 0; IncrementTimeStamp(); return (count); } public function Commit():void{ m_pairManager.Commit(); } private function IncrementTimeStamp():void{ var i:uint; if (m_timeStamp == b2Settings.USHRT_MAX){ i = 0; while (i < m_proxyPool.length) { (m_proxyPool[i] as b2Proxy).timeStamp = 0; i++; }; m_timeStamp = 1; } else { m_timeStamp++; }; } private function Query(lowerQueryOut:Array, upperQueryOut:Array, lowerValue:uint, upperValue:uint, bounds:Array, boundCount:uint, axis:int):void{ var bound:b2Bound; var i:int; var s:int; var proxy:b2Proxy; var lowerQuery:uint = BinarySearch(bounds, boundCount, lowerValue); var upperQuery:uint = BinarySearch(bounds, boundCount, upperValue); var j:uint = lowerQuery; while (j < upperQuery) { bound = bounds[j]; if (bound.IsLower()){ IncrementOverlapCount(bound.proxy); }; j++; }; if (lowerQuery > 0){ i = (lowerQuery - 1); bound = bounds[i]; s = bound.stabbingCount; while (s) { bound = bounds[i]; if (bound.IsLower()){ proxy = bound.proxy; if (lowerQuery <= proxy.upperBounds[axis]){ IncrementOverlapCount(bound.proxy); s--; }; }; i--; }; }; lowerQueryOut[0] = lowerQuery; upperQueryOut[0] = upperQuery; } private function AddProxyResult(proxy:b2Proxy, maxCount:Number, sortKey:Function):void{ var tempKey2:Number; var tempProxy2:b2Proxy; var key:Number = sortKey(proxy.userData); if (key < 0){ return; }; var i:Number = 0; while ((((i < m_queryResultCount)) && ((m_querySortKeys[i] < key)))) { i++; }; var tempKey:Number = key; var tempProxy:b2Proxy = proxy; m_queryResultCount = (m_queryResultCount + 1); if (m_queryResultCount > maxCount){ m_queryResultCount = maxCount; }; while (i < m_queryResultCount) { tempKey2 = m_querySortKeys[i]; tempProxy2 = m_queryResults[i]; m_querySortKeys[i] = tempKey; m_queryResults[i] = tempProxy; tempKey = tempKey2; tempProxy = tempProxy2; i++; }; } private function TestOverlapValidate(p1:b2Proxy, p2:b2Proxy):Boolean{ var bounds:Array; var bound1:b2Bound; var bound2:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; bound1 = bounds[p1.lowerBounds[axis]]; bound2 = bounds[p2.upperBounds[axis]]; if (bound1.value > bound2.value){ return (false); }; bound1 = bounds[p1.upperBounds[axis]]; bound2 = bounds[p2.lowerBounds[axis]]; if (bound1.value < bound2.value){ return (false); }; axis++; }; return (true); } private function ComputeBounds(lowerValues:Array, upperValues:Array, aabb:b2AABB):void{ var minVertexX:Number = aabb.lowerBound.x; var minVertexY:Number = aabb.lowerBound.y; minVertexX = b2Math.b2Min(minVertexX, m_worldAABB.upperBound.x); minVertexY = b2Math.b2Min(minVertexY, m_worldAABB.upperBound.y); minVertexX = b2Math.b2Max(minVertexX, m_worldAABB.lowerBound.x); minVertexY = b2Math.b2Max(minVertexY, m_worldAABB.lowerBound.y); var maxVertexX:Number = aabb.upperBound.x; var maxVertexY:Number = aabb.upperBound.y; maxVertexX = b2Math.b2Min(maxVertexX, m_worldAABB.upperBound.x); maxVertexY = b2Math.b2Min(maxVertexY, m_worldAABB.upperBound.y); maxVertexX = b2Math.b2Max(maxVertexX, m_worldAABB.lowerBound.x); maxVertexY = b2Math.b2Max(maxVertexY, m_worldAABB.lowerBound.y); lowerValues[0] = (uint((m_quantizationFactor.x * (minVertexX - m_worldAABB.lowerBound.x))) & (b2Settings.USHRT_MAX - 1)); upperValues[0] = ((uint((m_quantizationFactor.x * (maxVertexX - m_worldAABB.lowerBound.x))) & 0xFFFF) | 1); lowerValues[1] = (uint((m_quantizationFactor.y * (minVertexY - m_worldAABB.lowerBound.y))) & (b2Settings.USHRT_MAX - 1)); upperValues[1] = ((uint((m_quantizationFactor.y * (maxVertexY - m_worldAABB.lowerBound.y))) & 0xFFFF) | 1); } public function CreateProxy(aabb:b2AABB, userData):b2Proxy{ var index:uint; var proxy:b2Proxy; var i:int; var j:int; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerIndexOut:Array; var upperIndexOut:Array; var tBound1:b2Bound; var tBound2:b2Bound; var tBoundAS3:b2Bound; var proxy2:b2Proxy; if (!m_freeProxy){ m_freeProxy = (m_proxyPool[m_proxyCount] = new b2Proxy()); m_freeProxy.next = null; m_freeProxy.timeStamp = 0; m_freeProxy.overlapCount = b2_invalid; m_freeProxy.userData = null; i = 0; while (i < 2) { j = (m_proxyCount * 2); var _temp1 = j; j = (j + 1); var _local20 = _temp1; m_bounds[i][_local20] = new b2Bound(); m_bounds[i][j] = new b2Bound(); i++; }; }; proxy = m_freeProxy; m_freeProxy = proxy.next; proxy.overlapCount = 0; proxy.userData = userData; var boundCount:uint = (2 * m_proxyCount); var lowerValues:Array = new Array(); var upperValues:Array = new Array(); ComputeBounds(lowerValues, upperValues, aabb); var axis:int; while (axis < 2) { bounds = m_bounds[axis]; lowerIndexOut = [lowerIndex]; upperIndexOut = [upperIndex]; Query(lowerIndexOut, upperIndexOut, lowerValues[axis], upperValues[axis], bounds, boundCount, axis); lowerIndex = lowerIndexOut[0]; upperIndex = upperIndexOut[0]; bounds.splice(upperIndex, 0, bounds[(bounds.length - 1)]); bounds.length--; bounds.splice(lowerIndex, 0, bounds[(bounds.length - 1)]); bounds.length--; upperIndex++; tBound1 = bounds[lowerIndex]; tBound2 = bounds[upperIndex]; tBound1.value = lowerValues[axis]; tBound1.proxy = proxy; tBound2.value = upperValues[axis]; tBound2.proxy = proxy; tBoundAS3 = bounds[int((lowerIndex - 1))]; tBound1.stabbingCount = ((lowerIndex == 0)) ? 0 : tBoundAS3.stabbingCount; tBoundAS3 = bounds[int((upperIndex - 1))]; tBound2.stabbingCount = tBoundAS3.stabbingCount; index = lowerIndex; while (index < upperIndex) { tBoundAS3 = bounds[index]; tBoundAS3.stabbingCount++; index++; }; index = lowerIndex; while (index < (boundCount + 2)) { tBound1 = bounds[index]; proxy2 = tBound1.proxy; if (tBound1.IsLower()){ proxy2.lowerBounds[axis] = index; } else { proxy2.upperBounds[axis] = index; }; index++; }; axis++; }; m_proxyCount++; i = 0; while (i < m_queryResultCount) { m_pairManager.AddBufferedPair(proxy, m_queryResults[i]); i++; }; m_pairManager.Commit(); m_queryResultCount = 0; IncrementTimeStamp(); return (proxy); } public function DestroyProxy(proxy:b2Proxy):void{ var tBound1:b2Bound; var tBound2:b2Bound; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerValue:uint; var upperValue:uint; var tEnd:int; var index:uint; var index2:int; var proxy2:b2Proxy; var boundCount:int = (2 * m_proxyCount); var axis:int; while (axis < 2) { bounds = m_bounds[axis]; lowerIndex = proxy.lowerBounds[axis]; upperIndex = proxy.upperBounds[axis]; tBound1 = bounds[lowerIndex]; lowerValue = tBound1.value; tBound2 = bounds[upperIndex]; upperValue = tBound2.value; bounds.splice(upperIndex, 1); bounds.splice(lowerIndex, 1); bounds.push(tBound1); bounds.push(tBound2); tEnd = (boundCount - 2); index = lowerIndex; while (index < tEnd) { tBound1 = bounds[index]; proxy2 = tBound1.proxy; if (tBound1.IsLower()){ proxy2.lowerBounds[axis] = index; } else { proxy2.upperBounds[axis] = index; }; index++; }; tEnd = (upperIndex - 1); index2 = lowerIndex; while (index2 < tEnd) { tBound1 = bounds[index2]; tBound1.stabbingCount--; index2++; }; Query([0], [0], lowerValue, upperValue, bounds, (boundCount - 2), axis); axis++; }; var i:int; while (i < m_queryResultCount) { m_pairManager.RemoveBufferedPair(proxy, m_queryResults[i]); i++; }; m_pairManager.Commit(); m_queryResultCount = 0; IncrementTimeStamp(); proxy.userData = null; proxy.overlapCount = b2_invalid; proxy.lowerBounds[0] = b2_invalid; proxy.lowerBounds[1] = b2_invalid; proxy.upperBounds[0] = b2_invalid; proxy.upperBounds[1] = b2_invalid; proxy.next = m_freeProxy; m_freeProxy = proxy; m_proxyCount--; } public function TestOverlap(b:b2BoundValues, p:b2Proxy):Boolean{ var bounds:Array; var bound:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; bound = bounds[p.upperBounds[axis]]; if (b.lowerValues[axis] > bound.value){ return (false); }; bound = bounds[p.lowerBounds[axis]]; if (b.upperValues[axis] < bound.value){ return (false); }; axis++; }; return (true); } public function Validate():void{ var pair:b2Pair; var proxy1:b2Proxy; var proxy2:b2Proxy; var overlap:Boolean; var bounds:b2Bound; var boundCount:uint; var stabbingCount:uint; var i:uint; var bound:b2Bound; var axis:int; while (axis < 2) { bounds = m_bounds[axis]; boundCount = (2 * m_proxyCount); stabbingCount = 0; i = 0; while (i < boundCount) { bound = bounds[i]; if (bound.IsLower() == true){ stabbingCount++; } else { stabbingCount--; }; i++; }; axis++; }; } private function IncrementOverlapCount(proxy:b2Proxy):void{ if (proxy.timeStamp < m_timeStamp){ proxy.timeStamp = m_timeStamp; proxy.overlapCount = 1; } else { proxy.overlapCount = 2; m_queryResults[m_queryResultCount] = proxy; m_queryResultCount++; }; } public function InRange(aabb:b2AABB):Boolean{ var dX:Number; var dY:Number; var d2X:Number; var d2Y:Number; dX = aabb.lowerBound.x; dY = aabb.lowerBound.y; dX = (dX - m_worldAABB.upperBound.x); dY = (dY - m_worldAABB.upperBound.y); d2X = m_worldAABB.lowerBound.x; d2Y = m_worldAABB.lowerBound.y; d2X = (d2X - aabb.upperBound.x); d2Y = (d2Y - aabb.upperBound.y); dX = b2Math.b2Max(dX, d2X); dY = b2Math.b2Max(dY, d2Y); return ((b2Math.b2Max(dX, dY) < 0)); } public function QuerySegment(segment:b2Segment, userData, maxCount:int, sortKey:Function):int{ var xIndex:int; var yIndex:int; var proxy:b2Proxy; var lowerIndex:uint; var upperIndex:uint; var count:int; var i:Number; var A:Number; var B:Number; var tempValue:b2Proxy; var xProgress:Number; var yProgress:Number; var maxLamda:Number = 1; var dx:Number = ((segment.p2.x - segment.p1.x) * m_quantizationFactor.x); var dy:Number = ((segment.p2.y - segment.p1.y) * m_quantizationFactor.y); var sx:int = ((dx < -(Number.MIN_VALUE))) ? -1 : ((dx > Number.MIN_VALUE)) ? 1 : 0; var sy:int = ((dy < -(Number.MIN_VALUE))) ? -1 : ((dy > Number.MIN_VALUE)) ? 1 : 0; var p1x:Number = (m_quantizationFactor.x * (segment.p1.x - m_worldAABB.lowerBound.x)); var p1y:Number = (m_quantizationFactor.y * (segment.p1.y - m_worldAABB.lowerBound.y)); var startValues:Array = new Array(); var startValues2:Array = new Array(); startValues[0] = (uint(p1x) & (b2Settings.USHRT_MAX - 1)); startValues[1] = (uint(p1y) & (b2Settings.USHRT_MAX - 1)); startValues2[0] = (startValues[0] + 1); startValues2[1] = (startValues[1] + 1); var startIndices:Array = new Array(); var lowerIndexOut:Array = [lowerIndex]; var upperIndexOut:Array = [upperIndex]; Query(lowerIndexOut, upperIndexOut, startValues[0], startValues2[0], m_bounds[0], (2 * m_proxyCount), 0); if (sx >= 0){ xIndex = (upperIndexOut[0] - 1); } else { xIndex = lowerIndexOut[0]; }; Query(lowerIndexOut, upperIndexOut, startValues[1], startValues2[1], m_bounds[1], (2 * m_proxyCount), 1); if (sy >= 0){ yIndex = (upperIndexOut[0] - 1); } else { yIndex = lowerIndexOut[0]; }; if (sortKey != null){ i = 0; while (i < m_queryResultCount) { m_querySortKeys[i] = sortKey(m_queryResults[i].userData); i++; }; i = 0; while (i < (m_queryResultCount - 1)) { A = m_querySortKeys[i]; B = m_querySortKeys[(i + 1)]; if (((A)<0) ? (B >= 0) : (((A > B)) && ((B >= 0)))){ m_querySortKeys[(i + 1)] = A; m_querySortKeys[i] = B; tempValue = m_queryResults[(i + 1)]; m_queryResults[(i + 1)] = m_queryResults[i]; m_queryResults[i] = tempValue; i--; if (i == -1){ i = 1; }; } else { i++; }; }; while ((((m_queryResultCount > 0)) && ((m_querySortKeys[(m_queryResultCount - 1)] < 0)))) { m_queryResultCount--; }; }; while (true) { xProgress = 0; yProgress = 0; xIndex = (xIndex + ((sx >= 0)) ? 1 : -1); if ((((xIndex < 0)) || ((xIndex >= (m_proxyCount * 2))))){ break; }; if (sx != 0){ xProgress = ((m_bounds[0][xIndex].value - p1x) / dx); }; yIndex = (yIndex + ((sy >= 0)) ? 1 : -1); if ((((yIndex < 0)) || ((yIndex >= (m_proxyCount * 2))))){ break; }; if (sy != 0){ yProgress = ((m_bounds[1][yIndex].value - p1y) / dy); }; while (true) { if ((((sy == 0)) || (((!((sx == 0))) && ((xProgress < yProgress)))))){ if (xProgress > maxLamda){ break; }; if (((sx > 0)) ? m_bounds[0][xIndex].IsLower() : m_bounds[0][xIndex].IsUpper()){ proxy = m_bounds[0][xIndex].proxy; if (sy >= 0){ if ((((proxy.lowerBounds[1] <= (yIndex - 1))) && ((proxy.upperBounds[1] >= yIndex)))){ if (sortKey != null){ AddProxyResult(proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxy; m_queryResultCount++; }; }; } else { if ((((proxy.lowerBounds[1] <= yIndex)) && ((proxy.upperBounds[1] >= (yIndex + 1))))){ if (sortKey != null){ AddProxyResult(proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxy; m_queryResultCount++; }; }; }; }; if (((((((!((sortKey == null))) && ((m_queryResultCount == maxCount)))) && ((m_queryResultCount > 0)))) && ((xProgress > m_querySortKeys[(m_queryResultCount - 1)])))){ break; }; if (sx > 0){ xIndex++; if (xIndex == (m_proxyCount * 2)){ break; }; } else { xIndex--; if (xIndex < 0){ break; }; }; xProgress = ((m_bounds[0][xIndex].value - p1x) / dx); } else { if (yProgress > maxLamda){ break; }; if (((sy > 0)) ? m_bounds[1][yIndex].IsLower() : m_bounds[1][yIndex].IsUpper()){ proxy = m_bounds[1][yIndex].proxy; if (sx >= 0){ if ((((proxy.lowerBounds[0] <= (xIndex - 1))) && ((proxy.upperBounds[0] >= xIndex)))){ if (sortKey != null){ AddProxyResult(proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxy; m_queryResultCount++; }; }; } else { if ((((proxy.lowerBounds[0] <= xIndex)) && ((proxy.upperBounds[0] >= (xIndex + 1))))){ if (sortKey != null){ AddProxyResult(proxy, maxCount, sortKey); } else { m_queryResults[m_queryResultCount] = proxy; m_queryResultCount++; }; }; }; }; if (((((((!((sortKey == null))) && ((m_queryResultCount == maxCount)))) && ((m_queryResultCount > 0)))) && ((yProgress > m_querySortKeys[(m_queryResultCount - 1)])))){ break; }; if (sy > 0){ yIndex++; if (yIndex == (m_proxyCount * 2)){ break; }; } else { yIndex--; if (yIndex < 0){ break; }; }; yProgress = ((m_bounds[1][yIndex].value - p1y) / dy); }; }; break; }; count = 0; i = 0; while ((((i < m_queryResultCount)) && ((count < maxCount)))) { proxy = m_queryResults[i]; userData[i] = proxy.userData; i++; count++; }; m_queryResultCount = 0; IncrementTimeStamp(); return (count); } public function MoveProxy(proxy:b2Proxy, aabb:b2AABB):void{ var as3arr:Array; var as3int:int; var axis:uint; var index:uint; var bound:b2Bound; var prevBound:b2Bound; var nextBound:b2Bound; var nextProxyId:uint; var nextProxy:b2Proxy; var bounds:Array; var lowerIndex:uint; var upperIndex:uint; var lowerValue:uint; var upperValue:uint; var deltaLower:int; var deltaUpper:int; var prevProxy:b2Proxy; if (proxy == null){ return; }; if (aabb.IsValid() == false){ return; }; var boundCount:uint = (2 * m_proxyCount); var newValues:b2BoundValues = new b2BoundValues(); ComputeBounds(newValues.lowerValues, newValues.upperValues, aabb); var oldValues:b2BoundValues = new b2BoundValues(); axis = 0; while (axis < 2) { bound = m_bounds[axis][proxy.lowerBounds[axis]]; oldValues.lowerValues[axis] = bound.value; bound = m_bounds[axis][proxy.upperBounds[axis]]; oldValues.upperValues[axis] = bound.value; axis++; }; axis = 0; while (axis < 2) { bounds = m_bounds[axis]; lowerIndex = proxy.lowerBounds[axis]; upperIndex = proxy.upperBounds[axis]; lowerValue = newValues.lowerValues[axis]; upperValue = newValues.upperValues[axis]; bound = bounds[lowerIndex]; deltaLower = (lowerValue - bound.value); bound.value = lowerValue; bound = bounds[upperIndex]; deltaUpper = (upperValue - bound.value); bound.value = upperValue; if (deltaLower < 0){ index = lowerIndex; while ((((index > 0)) && ((lowerValue < (bounds[int((index - 1))] as b2Bound).value)))) { bound = bounds[index]; prevBound = bounds[int((index - 1))]; prevProxy = prevBound.proxy; prevBound.stabbingCount++; if (prevBound.IsUpper() == true){ if (TestOverlap(newValues, prevProxy)){ m_pairManager.AddBufferedPair(proxy, prevProxy); }; as3arr = prevProxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount++; } else { as3arr = prevProxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount--; }; as3arr = proxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.Swap(prevBound); index--; }; }; if (deltaUpper > 0){ index = upperIndex; while ((((index < (boundCount - 1))) && (((bounds[int((index + 1))] as b2Bound).value <= upperValue)))) { bound = bounds[index]; nextBound = bounds[int((index + 1))]; nextProxy = nextBound.proxy; nextBound.stabbingCount++; if (nextBound.IsLower() == true){ if (TestOverlap(newValues, nextProxy)){ m_pairManager.AddBufferedPair(proxy, nextProxy); }; as3arr = nextProxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount++; } else { as3arr = nextProxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount--; }; as3arr = proxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.Swap(nextBound); index++; }; }; if (deltaLower > 0){ index = lowerIndex; while ((((index < (boundCount - 1))) && (((bounds[int((index + 1))] as b2Bound).value <= lowerValue)))) { bound = bounds[index]; nextBound = bounds[int((index + 1))]; nextProxy = nextBound.proxy; nextBound.stabbingCount--; if (nextBound.IsUpper()){ if (TestOverlap(oldValues, nextProxy)){ m_pairManager.RemoveBufferedPair(proxy, nextProxy); }; as3arr = nextProxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount--; } else { as3arr = nextProxy.lowerBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.stabbingCount++; }; as3arr = proxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.Swap(nextBound); index++; }; }; if (deltaUpper < 0){ index = upperIndex; while ((((index > 0)) && ((upperValue < (bounds[int((index - 1))] as b2Bound).value)))) { bound = bounds[index]; prevBound = bounds[int((index - 1))]; prevProxy = prevBound.proxy; prevBound.stabbingCount--; if (prevBound.IsLower() == true){ if (TestOverlap(oldValues, prevProxy)){ m_pairManager.RemoveBufferedPair(proxy, prevProxy); }; as3arr = prevProxy.lowerBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount--; } else { as3arr = prevProxy.upperBounds; as3int = as3arr[axis]; as3int++; as3arr[axis] = as3int; bound.stabbingCount++; }; as3arr = proxy.upperBounds; as3int = as3arr[axis]; as3int--; as3arr[axis] = as3int; bound.Swap(prevBound); index--; }; }; axis++; }; } public static function BinarySearch(bounds:Array, count:int, value:uint):uint{ var mid:int; var bound:b2Bound; var low:int; var high:int = (count - 1); while (low <= high) { mid = ((low + high) / 2); bound = bounds[mid]; if (bound.value > value){ high = (mid - 1); } else { if (bound.value < value){ low = (mid + 1); } else { return (uint(mid)); }; }; }; return (uint(low)); } } }//package Box2D.Collision
Section 15
//b2Collision (Box2D.Collision.b2Collision) package Box2D.Collision { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2Collision { public static const b2_nullFeature:uint = 0xFF; private static var b2CollidePolyTempVec:b2Vec2 = new b2Vec2(); public function b2Collision(){ super(); } public static function EdgeSeparation(poly1:b2PolygonShape, xf1:b2XForm, edge1:int, poly2:b2PolygonShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dot:Number; var count1:int = poly1.m_vertexCount; var vertices1:Array = poly1.m_vertices; var normals1:Array = poly1.m_normals; var count2:int = poly2.m_vertexCount; var vertices2:Array = poly2.m_vertices; tMat = xf1.R; tVec = normals1[edge1]; var normal1WorldX:Number = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); var normal1WorldY:Number = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = xf2.R; var normal1X:Number = ((tMat.col1.x * normal1WorldX) + (tMat.col1.y * normal1WorldY)); var normal1Y:Number = ((tMat.col2.x * normal1WorldX) + (tMat.col2.y * normal1WorldY)); var index:int; var minDot:Number = Number.MAX_VALUE; var i:int; while (i < count2) { tVec = vertices2[i]; dot = ((tVec.x * normal1X) + (tVec.y * normal1Y)); if (dot < minDot){ minDot = dot; index = i; }; i++; }; tVec = vertices1[edge1]; tMat = xf1.R; var v1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var v1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tVec = vertices2[index]; tMat = xf2.R; var v2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var v2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); v2X = (v2X - v1X); v2Y = (v2Y - v1Y); var separation:Number = ((v2X * normal1WorldX) + (v2Y * normal1WorldY)); return (separation); } public static function b2TestOverlap(a:b2AABB, b:b2AABB):Boolean{ var t1:b2Vec2 = b.lowerBound; var t2:b2Vec2 = a.upperBound; var d1X:Number = (t1.x - t2.x); var d1Y:Number = (t1.y - t2.y); t1 = a.lowerBound; t2 = b.upperBound; var d2X:Number = (t1.x - t2.x); var d2Y:Number = (t1.y - t2.y); if ((((d1X > 0)) || ((d1Y > 0)))){ return (false); }; if ((((d2X > 0)) || ((d2Y > 0)))){ return (false); }; return (true); } public static function FindIncidentEdge(c:Array, poly1:b2PolygonShape, xf1:b2XForm, edge1:int, poly2:b2PolygonShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var tClip:ClipVertex; var dot:Number; var count1:int = poly1.m_vertexCount; var normals1:Array = poly1.m_normals; var count2:int = poly2.m_vertexCount; var vertices2:Array = poly2.m_vertices; var normals2:Array = poly2.m_normals; tMat = xf1.R; tVec = normals1[edge1]; var normal1X:Number = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); var normal1Y:Number = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = xf2.R; var tX:Number = ((tMat.col1.x * normal1X) + (tMat.col1.y * normal1Y)); normal1Y = ((tMat.col2.x * normal1X) + (tMat.col2.y * normal1Y)); normal1X = tX; var index:int; var minDot:Number = Number.MAX_VALUE; var i:int; while (i < count2) { tVec = normals2[i]; dot = ((normal1X * tVec.x) + (normal1Y * tVec.y)); if (dot < minDot){ minDot = dot; index = i; }; i++; }; var i1:int = index; var i2:int = (((i1 + 1) < count2)) ? (i1 + 1) : 0; tClip = c[0]; tVec = vertices2[i1]; tMat = xf2.R; tClip.v.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); tClip.v.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tClip.id.features.referenceEdge = edge1; tClip.id.features.incidentEdge = i1; tClip.id.features.incidentVertex = 0; tClip = c[1]; tVec = vertices2[i2]; tMat = xf2.R; tClip.v.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); tClip.v.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tClip.id.features.referenceEdge = edge1; tClip.id.features.incidentEdge = i2; tClip.id.features.incidentVertex = 1; } public static function b2CollidePolygons(manifold:b2Manifold, polyA:b2PolygonShape, xfA:b2XForm, polyB:b2PolygonShape, xfB:b2XForm):void{ var cv:ClipVertex; var poly1:b2PolygonShape; var poly2:b2PolygonShape; var edge1:int; var flip:uint; var np:int; var v12:b2Vec2; var separation:Number; var cp:b2ManifoldPoint; manifold.pointCount = 0; var edgeA:int; var edgeAO:Array = [edgeA]; var separationA:Number = FindMaxSeparation(edgeAO, polyA, xfA, polyB, xfB); edgeA = edgeAO[0]; if (separationA > 0){ return; }; var edgeB:int; var edgeBO:Array = [edgeB]; var separationB:Number = FindMaxSeparation(edgeBO, polyB, xfB, polyA, xfA); edgeB = edgeBO[0]; if (separationB > 0){ return; }; var xf1:b2XForm = new b2XForm(); var xf2:b2XForm = new b2XForm(); var k_relativeTol:Number = 0.98; var k_absoluteTol:Number = 0.001; if (separationB > ((k_relativeTol * separationA) + k_absoluteTol)){ poly1 = polyB; poly2 = polyA; xf1.Set(xfB); xf2.Set(xfA); edge1 = edgeB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1.Set(xfA); xf2.Set(xfB); edge1 = edgeA; flip = 0; }; var incidentEdge:Array = [new ClipVertex(), new ClipVertex()]; FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1:int = poly1.m_vertexCount; var vertices1:Array = poly1.m_vertices; var tVec:b2Vec2 = vertices1[edge1]; var v11:b2Vec2 = tVec.Copy(); if ((edge1 + 1) < count1){ tVec = vertices1[int((edge1 + 1))]; v12 = tVec.Copy(); } else { tVec = vertices1[0]; v12 = tVec.Copy(); }; var dv:b2Vec2 = b2Math.SubtractVV(v12, v11); var sideNormal:b2Vec2 = b2Math.b2MulMV(xf1.R, b2Math.SubtractVV(v12, v11)); sideNormal.Normalize(); var frontNormal:b2Vec2 = b2Math.b2CrossVF(sideNormal, 1); v11 = b2Math.b2MulX(xf1, v11); v12 = b2Math.b2MulX(xf1, v12); var frontOffset:Number = b2Math.b2Dot(frontNormal, v11); var sideOffset1:Number = -(b2Math.b2Dot(sideNormal, v11)); var sideOffset2:Number = b2Math.b2Dot(sideNormal, v12); var clipPoints1:Array = [new ClipVertex(), new ClipVertex()]; var clipPoints2:Array = [new ClipVertex(), new ClipVertex()]; np = ClipSegmentToLine(clipPoints1, incidentEdge, sideNormal.Negative(), sideOffset1); if (np < 2){ return; }; np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormal, sideOffset2); if (np < 2){ return; }; manifold.normal = (flip) ? frontNormal.Negative() : frontNormal.Copy(); var pointCount:int; var i:int; while (i < b2Settings.b2_maxManifoldPoints) { cv = clipPoints2[i]; separation = (((frontNormal.x * cv.v.x) + (frontNormal.y * cv.v.y)) - frontOffset); if (separation <= 0){ cp = manifold.points[pointCount]; cp.separation = separation; cp.localPoint1 = b2Math.b2MulXT(xfA, cv.v); cp.localPoint2 = b2Math.b2MulXT(xfB, cv.v); cp.id.key = cv.id._key; cp.id.features.flip = flip; pointCount++; }; i++; }; manifold.pointCount = pointCount; } public static function FindMaxSeparation(edgeIndex:Array, poly1:b2PolygonShape, xf1:b2XForm, poly2:b2PolygonShape, xf2:b2XForm):Number{ var tVec:b2Vec2; var tMat:b2Mat22; var bestEdge:int; var bestSeparation:Number; var increment:int; var dot:Number; var count1:int = poly1.m_vertexCount; var normals1:Array = poly1.m_normals; tMat = xf2.R; tVec = poly2.m_centroid; var dX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var dY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf1.R; tVec = poly1.m_centroid; dX = (dX - (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)))); dY = (dY - (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)))); var dLocal1X:Number = ((dX * xf1.R.col1.x) + (dY * xf1.R.col1.y)); var dLocal1Y:Number = ((dX * xf1.R.col2.x) + (dY * xf1.R.col2.y)); var edge:int; var maxDot:Number = -(Number.MAX_VALUE); var i:int; while (i < count1) { tVec = normals1[i]; dot = ((tVec.x * dLocal1X) + (tVec.y * dLocal1Y)); if (dot > maxDot){ maxDot = dot; edge = i; }; i++; }; var s:Number = EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (s > 0){ return (s); }; var prevEdge:int = (((edge - 1) >= 0)) ? (edge - 1) : (count1 - 1); var sPrev:Number = EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); if (sPrev > 0){ return (sPrev); }; var nextEdge:int = (((edge + 1) < count1)) ? (edge + 1) : 0; var sNext:Number = EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); if (sNext > 0){ return (sNext); }; if ((((sPrev > s)) && ((sPrev > sNext)))){ increment = -1; bestEdge = prevEdge; bestSeparation = sPrev; } else { if (sNext > s){ increment = 1; bestEdge = nextEdge; bestSeparation = sNext; } else { edgeIndex[0] = edge; return (s); }; }; while (true) { if (increment == -1){ edge = (((bestEdge - 1) >= 0)) ? (bestEdge - 1) : (count1 - 1); } else { edge = (((bestEdge + 1) < count1)) ? (bestEdge + 1) : 0; }; s = EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (s > 0){ return (s); }; if (s > bestSeparation){ bestEdge = edge; bestSeparation = s; } else { break; }; }; edgeIndex[0] = bestEdge; return (bestSeparation); } public static function ClipSegmentToLine(vOut:Array, vIn:Array, normal:b2Vec2, offset:Number):int{ var cv:ClipVertex; var numOut:int; var vIn0:b2Vec2; var vIn1:b2Vec2; var distance0:Number; var interp:Number; var tVec:b2Vec2; var cv2:ClipVertex; numOut = 0; cv = vIn[0]; vIn0 = cv.v; cv = vIn[1]; vIn1 = cv.v; distance0 = (b2Math.b2Dot(normal, vIn0) - offset); var distance1:Number = (b2Math.b2Dot(normal, vIn1) - offset); if (distance0 <= 0){ var _temp1 = numOut; numOut = (numOut + 1); var _local14 = _temp1; vOut[_local14] = vIn[0]; }; if (distance1 <= 0){ var _temp2 = numOut; numOut = (numOut + 1); _local14 = _temp2; vOut[_local14] = vIn[1]; }; if ((distance0 * distance1) < 0){ interp = (distance0 / (distance0 - distance1)); cv = vOut[numOut]; tVec = cv.v; tVec.x = (vIn0.x + (interp * (vIn1.x - vIn0.x))); tVec.y = (vIn0.y + (interp * (vIn1.y - vIn0.y))); cv = vOut[numOut]; if (distance0 > 0){ cv2 = vIn[0]; cv.id = cv2.id; } else { cv2 = vIn[1]; cv.id = cv2.id; }; numOut++; }; return (numOut); } public static function b2CollideCircles(manifold:b2Manifold, circle1:b2CircleShape, xf1:b2XForm, circle2:b2CircleShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var separation:Number; var dist:Number; var a:Number; manifold.pointCount = 0; tMat = xf1.R; tVec = circle1.m_localPosition; var p1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf2.R; tVec = circle2.m_localPosition; var p2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var distSqr:Number = ((dX * dX) + (dY * dY)); var r1:Number = circle1.m_radius; var r2:Number = circle2.m_radius; var radiusSum:Number = (r1 + r2); if (distSqr > (radiusSum * radiusSum)){ return; }; if (distSqr < Number.MIN_VALUE){ separation = -(radiusSum); manifold.normal.Set(0, 1); } else { dist = Math.sqrt(distSqr); separation = (dist - radiusSum); a = (1 / dist); manifold.normal.x = (a * dX); manifold.normal.y = (a * dY); }; manifold.pointCount = 1; var tPoint:b2ManifoldPoint = manifold.points[0]; tPoint.id.key = 0; tPoint.separation = separation; p1X = (p1X + (r1 * manifold.normal.x)); p1Y = (p1Y + (r1 * manifold.normal.y)); p2X = (p2X - (r2 * manifold.normal.x)); p2Y = (p2Y - (r2 * manifold.normal.y)); var pX:Number = (0.5 * (p1X + p2X)); var pY:Number = (0.5 * (p1Y + p2Y)); var tX:Number = (pX - xf1.position.x); var tY:Number = (pY - xf1.position.y); tPoint.localPoint1.x = ((tX * xf1.R.col1.x) + (tY * xf1.R.col1.y)); tPoint.localPoint1.y = ((tX * xf1.R.col2.x) + (tY * xf1.R.col2.y)); tX = (pX - xf2.position.x); tY = (pY - xf2.position.y); tPoint.localPoint2.x = ((tX * xf2.R.col1.x) + (tY * xf2.R.col1.y)); tPoint.localPoint2.y = ((tX * xf2.R.col2.x) + (tY * xf2.R.col2.y)); } public static function b2CollidePolygonAndCircle(manifold:b2Manifold, polygon:b2PolygonShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):void{ var tPoint:b2ManifoldPoint; var dX:Number; var dY:Number; var positionX:Number; var positionY:Number; var tVec:b2Vec2; var tMat:b2Mat22; var dist:Number; var pX:Number; var pY:Number; var s:Number; manifold.pointCount = 0; tMat = xf2.R; tVec = circle.m_localPosition; var cX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var cY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); dX = (cX - xf1.position.x); dY = (cY - xf1.position.y); tMat = xf1.R; var cLocalX:Number = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); var cLocalY:Number = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); var normalIndex:int; var separation:Number = -(Number.MAX_VALUE); var radius:Number = circle.m_radius; var vertexCount:int = polygon.m_vertexCount; var vertices:Array = polygon.m_vertices; var normals:Array = polygon.m_normals; var i:int; while (i < vertexCount) { tVec = vertices[i]; dX = (cLocalX - tVec.x); dY = (cLocalY - tVec.y); tVec = normals[i]; s = ((tVec.x * dX) + (tVec.y * dY)); if (s > radius){ return; }; if (s > separation){ separation = s; normalIndex = i; }; i++; }; if (separation < Number.MIN_VALUE){ manifold.pointCount = 1; tVec = normals[normalIndex]; tMat = xf1.R; manifold.normal.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); manifold.normal.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tPoint = manifold.points[0]; tPoint.id.features.incidentEdge = normalIndex; tPoint.id.features.incidentVertex = b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; positionX = (cX - (radius * manifold.normal.x)); positionY = (cY - (radius * manifold.normal.y)); dX = (positionX - xf1.position.x); dY = (positionY - xf1.position.y); tMat = xf1.R; tPoint.localPoint1.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint1.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); dX = (positionX - xf2.position.x); dY = (positionY - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint2.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); tPoint.separation = (separation - radius); return; }; var vertIndex1:int = normalIndex; var vertIndex2:int = (((vertIndex1 + 1) < vertexCount)) ? (vertIndex1 + 1) : 0; tVec = vertices[vertIndex1]; var tVec2:b2Vec2 = vertices[vertIndex2]; var eX:Number = (tVec2.x - tVec.x); var eY:Number = (tVec2.y - tVec.y); var length:Number = Math.sqrt(((eX * eX) + (eY * eY))); eX = (eX / length); eY = (eY / length); dX = (cLocalX - tVec.x); dY = (cLocalY - tVec.y); var u:Number = ((dX * eX) + (dY * eY)); tPoint = manifold.points[0]; if (u <= 0){ pX = tVec.x; pY = tVec.y; tPoint.id.features.incidentEdge = b2_nullFeature; tPoint.id.features.incidentVertex = vertIndex1; } else { if (u >= length){ pX = tVec2.x; pY = tVec2.y; tPoint.id.features.incidentEdge = b2_nullFeature; tPoint.id.features.incidentVertex = vertIndex2; } else { pX = ((eX * u) + tVec.x); pY = ((eY * u) + tVec.y); tPoint.id.features.incidentEdge = normalIndex; tPoint.id.features.incidentVertex = b2_nullFeature; }; }; dX = (cLocalX - pX); dY = (cLocalY - pY); dist = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dist); dY = (dY / dist); if (dist > radius){ return; }; manifold.pointCount = 1; tMat = xf1.R; manifold.normal.x = ((tMat.col1.x * dX) + (tMat.col2.x * dY)); manifold.normal.y = ((tMat.col1.y * dX) + (tMat.col2.y * dY)); positionX = (cX - (radius * manifold.normal.x)); positionY = (cY - (radius * manifold.normal.y)); dX = (positionX - xf1.position.x); dY = (positionY - xf1.position.y); tMat = xf1.R; tPoint.localPoint1.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint1.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); dX = (positionX - xf2.position.x); dY = (positionY - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((dX * tMat.col1.x) + (dY * tMat.col1.y)); tPoint.localPoint2.y = ((dX * tMat.col2.x) + (dY * tMat.col2.y)); tPoint.separation = (dist - radius); tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; } } }//package Box2D.Collision
Section 16
//b2ContactID (Box2D.Collision.b2ContactID) package Box2D.Collision { import Box2D.Common.*; public class b2ContactID { b2internal var _key:uint; public var features:Features; public function b2ContactID(){ features = new Features(); super(); features._m_id = this; } public function Set(id:b2ContactID):void{ key = id._key; } public function Copy():b2ContactID{ var id:b2ContactID = new b2ContactID(); id.key = key; return (id); } public function set key(value:uint):void{ _key = value; features._referenceEdge = (_key & 0xFF); features._incidentEdge = (((_key & 0xFF00) >> 8) & 0xFF); features._incidentVertex = (((_key & 0xFF0000) >> 16) & 0xFF); features._flip = (((_key & 4278190080) >> 24) & 0xFF); } public function get key():uint{ return (_key); } } }//package Box2D.Collision
Section 17
//b2ContactPoint (Box2D.Collision.b2ContactPoint) package Box2D.Collision { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class b2ContactPoint { public var friction:Number; public var separation:Number; public var normal:b2Vec2; public var position:b2Vec2; public var restitution:Number; public var shape1:b2Shape; public var shape2:b2Shape; public var id:b2ContactID; public var velocity:b2Vec2; public function b2ContactPoint(){ position = new b2Vec2(); velocity = new b2Vec2(); normal = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Collision
Section 18
//b2Distance (Box2D.Collision.b2Distance) package Box2D.Collision { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2Distance { private static var s_p2s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var s_p1s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var s_points:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()]; private static var gPoint:b2Point = new b2Point(); public static var g_GJK_Iterations:int = 0; public function b2Distance(){ super(); } public static function InPoints(w:b2Vec2, points:Array, pointCount:int):Boolean{ var points_i:b2Vec2; var dX:Number; var dY:Number; var mX:Number; var mY:Number; var k_tolerance:Number = (100 * Number.MIN_VALUE); var i:int; while (i < pointCount) { points_i = points[i]; dX = (((w.x - points_i.x) < 0)) ? -((w.x - points_i.x)) : (w.x - points_i.x); dY = (((w.y - points_i.y) < 0)) ? -((w.y - points_i.y)) : (w.y - points_i.y); mX = ((w.x < 0)) ? -(w.x) : (((w.x > points_i.x) < 0)) ? -(points_i.x) : (points_i.x) ? ((w.x < 0)) ? -(w.x) : w.x : ((points_i.x < 0)) ? -(points_i.x) : points_i.x; mY = ((w.x < 0)) ? -(w.y) : (((w.y > points_i.y) < 0)) ? -(points_i.y) : (points_i.y) ? ((w.y < 0)) ? -(w.y) : w.y : ((points_i.y < 0)) ? -(points_i.y) : points_i.y; if ((((dX < (k_tolerance * (mX + 1)))) && ((dY < (k_tolerance * (mY + 1)))))){ return (true); }; i++; }; return (false); } public static function DistanceGeneric(x1:b2Vec2, x2:b2Vec2, shape1, xf1:b2XForm, shape2, xf2:b2XForm):Number{ var tVec:b2Vec2; var vX:Number; var vY:Number; var w1:b2Vec2; var w2:b2Vec2; var wX:Number; var wY:Number; var vw:Number; var maxSqr:Number; var i:int; var p1s:Array = s_p1s; var p2s:Array = s_p2s; var points:Array = s_points; var pointCount:int; x1.SetV(shape1.GetFirstVertex(xf1)); x2.SetV(shape2.GetFirstVertex(xf2)); var vSqr:Number = 0; var maxIterations = 20; var iter:int; while (iter < maxIterations) { vX = (x2.x - x1.x); vY = (x2.y - x1.y); w1 = shape1.Support(xf1, vX, vY); w2 = shape2.Support(xf2, -(vX), -(vY)); vSqr = ((vX * vX) + (vY * vY)); wX = (w2.x - w1.x); wY = (w2.y - w1.y); vw = ((vX * wX) + (vY * wY)); if ((vSqr - vw) <= (0.01 * vSqr)){ if (pointCount == 0){ x1.SetV(w1); x2.SetV(w2); }; g_GJK_Iterations = iter; return (Math.sqrt(vSqr)); }; switch (pointCount){ case 0: tVec = p1s[0]; tVec.SetV(w1); tVec = p2s[0]; tVec.SetV(w2); tVec = points[0]; tVec.x = wX; tVec.y = wY; x1.SetV(p1s[0]); x2.SetV(p2s[0]); pointCount++; break; case 1: tVec = p1s[1]; tVec.SetV(w1); tVec = p2s[1]; tVec.SetV(w2); tVec = points[1]; tVec.x = wX; tVec.y = wY; pointCount = ProcessTwo(x1, x2, p1s, p2s, points); break; case 2: tVec = p1s[2]; tVec.SetV(w1); tVec = p2s[2]; tVec.SetV(w2); tVec = points[2]; tVec.x = wX; tVec.y = wY; pointCount = ProcessThree(x1, x2, p1s, p2s, points); break; }; if (pointCount == 3){ g_GJK_Iterations = iter; return (0); }; maxSqr = -(Number.MAX_VALUE); i = 0; while (i < pointCount) { tVec = points[i]; maxSqr = b2Math.b2Max(maxSqr, ((tVec.x * tVec.x) + (tVec.y * tVec.y))); i++; }; if (vSqr <= ((100 * Number.MIN_VALUE) * maxSqr)){ g_GJK_Iterations = iter; vX = (x2.x - x1.x); vY = (x2.y - x1.y); vSqr = ((vX * vX) + (vY * vY)); return (Math.sqrt(vSqr)); }; iter++; }; g_GJK_Iterations = maxIterations; return (Math.sqrt(vSqr)); } public static function DistanceEdgeCircle(x1:b2Vec2, x2:b2Vec2, edge:b2EdgeShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):Number{ var vWorld:b2Vec2; var tMat:b2Mat22; var tVec:b2Vec2; var r:Number = (circle.m_radius - b2Settings.b2_toiSlop); tMat = xf2.R; tVec = circle.m_localPosition; var cWorldX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var cWorldY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf1.R; var tX:Number = (cWorldX - xf1.position.x); var tY:Number = (cWorldY - xf1.position.y); var cLocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var cLocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var dLen:Number = (((cLocalX - edge.m_coreV1.x) * edge.m_direction.x) + ((cLocalY - edge.m_coreV1.y) * edge.m_direction.y)); if (dLen <= 0){ tMat = xf1.R; tVec = edge.m_coreV1; x1.x = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); x1.y = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); } else { if (dLen >= edge.m_length){ tMat = xf1.R; tVec = edge.m_coreV2; x1.x = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); x1.y = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); } else { tMat = xf1.R; tX = (edge.m_coreV1.x + (dLen * edge.m_direction.x)); tY = (edge.m_coreV1.y + (dLen * edge.m_direction.y)); x1.x = (xf1.position.x + ((tMat.col1.x * tX) + (tMat.col2.x * tY))); x1.y = (xf1.position.y + ((tMat.col1.y * tX) + (tMat.col2.y * tY))); dLen = (((cLocalX - edge.m_coreV1.x) * edge.m_normal.x) + ((cLocalY - edge.m_coreV1.y) * edge.m_normal.y)); if (dLen < 0){ if (dLen < -(r)){ tMat = xf1.R; tX = (cLocalX + (r * edge.m_normal.x)); tY = (cLocalY + (r * edge.m_normal.y)); x2.x = (xf1.position.x + ((tMat.col1.x * tX) + (tMat.col2.x * tY))); x2.y = (xf1.position.y + ((tMat.col1.y * tX) + (tMat.col2.y * tY))); return ((-(dLen) - r)); }; x2.x = x1.x; x2.y = x1.y; return (0); } else { if (dLen > r){ tMat = xf1.R; tX = (cLocalX - (r * edge.m_normal.x)); tY = (cLocalY - (r * edge.m_normal.y)); x2.x = (xf1.position.x + ((tMat.col1.x * tX) + (tMat.col2.x * tY))); x2.y = (xf1.position.y + ((tMat.col1.y * tX) + (tMat.col2.y * tY))); return ((dLen - r)); }; x2.x = x1.x; x2.y = x1.y; return (0); }; }; }; tX = (cWorldX - x1.x); tY = (cWorldY - x1.y); dLen = ((tX * tX) + (tY * tY)); if (dLen > (r * r)){ dLen = Math.sqrt(dLen); x2.x = (cWorldX - ((r * tX) / dLen)); x2.y = (cWorldY - ((r * tY) / dLen)); return ((dLen - r)); }; x2.x = x1.x; x2.y = x1.y; return (0); } public static function DistanceCC(x1:b2Vec2, x2:b2Vec2, circle1:b2CircleShape, xf1:b2XForm, circle2:b2CircleShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dLen:Number; var distance:Number; tMat = xf1.R; tVec = circle1.m_localPosition; var p1X:Number = (xf1.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p1Y:Number = (xf1.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf2.R; tVec = circle2.m_localPosition; var p2X:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var p2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var dSqr:Number = ((dX * dX) + (dY * dY)); var r1:Number = (circle1.m_radius - b2Settings.b2_toiSlop); var r2:Number = (circle2.m_radius - b2Settings.b2_toiSlop); var r:Number = (r1 + r2); if (dSqr > (r * r)){ dLen = Math.sqrt(dSqr); dX = (dX / dLen); dY = (dY / dLen); distance = (dLen - r); x1.x = (p1X + (r1 * dX)); x1.y = (p1Y + (r1 * dY)); x2.x = (p2X - (r2 * dX)); x2.y = (p2Y - (r2 * dY)); return (distance); }; if (dSqr > (Number.MIN_VALUE * Number.MIN_VALUE)){ dLen = Math.sqrt(dSqr); dX = (dX / dLen); dY = (dY / dLen); x1.x = (p1X + (r1 * dX)); x1.y = (p1Y + (r1 * dY)); x2.x = x1.x; x2.y = x1.y; return (0); }; x1.x = p1X; x1.y = p1Y; x2.x = x1.x; x2.y = x1.y; return (0); } public static function ProcessThree(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int{ var points_0:b2Vec2; var points_1:b2Vec2; var points_2:b2Vec2; var p1s_0:b2Vec2; var p1s_1:b2Vec2; var p1s_2:b2Vec2; var p2s_0:b2Vec2; var p2s_1:b2Vec2; var lambda:Number; points_0 = points[0]; points_1 = points[1]; points_2 = points[2]; p1s_0 = p1s[0]; p1s_1 = p1s[1]; p1s_2 = p1s[2]; p2s_0 = p2s[0]; p2s_1 = p2s[1]; var p2s_2:b2Vec2 = p2s[2]; var aX:Number = points_0.x; var aY:Number = points_0.y; var bX:Number = points_1.x; var bY:Number = points_1.y; var cX:Number = points_2.x; var cY:Number = points_2.y; var abX:Number = (bX - aX); var abY:Number = (bY - aY); var acX:Number = (cX - aX); var acY:Number = (cY - aY); var bcX:Number = (cX - bX); var bcY:Number = (cY - bY); var sn:Number = -(((aX * abX) + (aY * abY))); var sd:Number = ((bX * abX) + (bY * abY)); var tn:Number = -(((aX * acX) + (aY * acY))); var td:Number = ((cX * acX) + (cY * acY)); var un:Number = -(((bX * bcX) + (bY * bcY))); var ud:Number = ((cX * bcX) + (cY * bcY)); if ((((td <= 0)) && ((ud <= 0)))){ x1.SetV(p1s_2); x2.SetV(p2s_2); p1s_0.SetV(p1s_2); p2s_0.SetV(p2s_2); points_0.SetV(points_2); return (1); }; var n:Number = ((abX * acY) - (abY * acX)); var vc:Number = (n * ((aX * bY) - (aY * bX))); var va:Number = (n * ((bX * cY) - (bY * cX))); if ((((((((va <= 0)) && ((un >= 0)))) && ((ud >= 0)))) && (((un + ud) > 0)))){ lambda = (un / (un + ud)); x1.x = (p1s_1.x + (lambda * (p1s_2.x - p1s_1.x))); x1.y = (p1s_1.y + (lambda * (p1s_2.y - p1s_1.y))); x2.x = (p2s_1.x + (lambda * (p2s_2.x - p2s_1.x))); x2.y = (p2s_1.y + (lambda * (p2s_2.y - p2s_1.y))); p1s_0.SetV(p1s_2); p2s_0.SetV(p2s_2); points_0.SetV(points_2); return (2); }; var vb:Number = (n * ((cX * aY) - (cY * aX))); if ((((((((vb <= 0)) && ((tn >= 0)))) && ((td >= 0)))) && (((tn + td) > 0)))){ lambda = (tn / (tn + td)); x1.x = (p1s_0.x + (lambda * (p1s_2.x - p1s_0.x))); x1.y = (p1s_0.y + (lambda * (p1s_2.y - p1s_0.y))); x2.x = (p2s_0.x + (lambda * (p2s_2.x - p2s_0.x))); x2.y = (p2s_0.y + (lambda * (p2s_2.y - p2s_0.y))); p1s_1.SetV(p1s_2); p2s_1.SetV(p2s_2); points_1.SetV(points_2); return (2); }; var denom:Number = ((va + vb) + vc); denom = (1 / denom); var u:Number = (va * denom); var v:Number = (vb * denom); var w:Number = ((1 - u) - v); x1.x = (((u * p1s_0.x) + (v * p1s_1.x)) + (w * p1s_2.x)); x1.y = (((u * p1s_0.y) + (v * p1s_1.y)) + (w * p1s_2.y)); x2.x = (((u * p2s_0.x) + (v * p2s_1.x)) + (w * p2s_2.x)); x2.y = (((u * p2s_0.y) + (v * p2s_1.y)) + (w * p2s_2.y)); return (3); } public static function DistancePC(x1:b2Vec2, x2:b2Vec2, polygon:b2PolygonShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):Number{ var tMat:b2Mat22; var tVec:b2Vec2; var dX:Number; var dY:Number; var dLen:Number; var point:b2Point = gPoint; tVec = circle.m_localPosition; tMat = xf2.R; point.p.x = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); point.p.y = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var distance:Number = DistanceGeneric(x1, x2, polygon, xf1, point, b2Math.b2XForm_identity); var r:Number = (circle.m_radius - b2Settings.b2_toiSlop); if (distance > r){ distance = (distance - r); dX = (x2.x - x1.x); dY = (x2.y - x1.y); dLen = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / dLen); dY = (dY / dLen); x2.x = (x2.x - (r * dX)); x2.y = (x2.y - (r * dY)); } else { distance = 0; x2.x = x1.x; x2.y = x1.y; }; return (distance); } public static function Distance(x1:b2Vec2, x2:b2Vec2, shape1:b2Shape, xf1:b2XForm, shape2:b2Shape, xf2:b2XForm):Number{ var type1:int = shape1.m_type; var type2:int = shape2.m_type; if ((((type1 == b2Shape.e_circleShape)) && ((type2 == b2Shape.e_circleShape)))){ return (DistanceCC(x1, x2, (shape1 as b2CircleShape), xf1, (shape2 as b2CircleShape), xf2)); }; if ((((type1 == b2Shape.e_polygonShape)) && ((type2 == b2Shape.e_circleShape)))){ return (DistancePC(x1, x2, (shape1 as b2PolygonShape), xf1, (shape2 as b2CircleShape), xf2)); }; if ((((type1 == b2Shape.e_circleShape)) && ((type2 == b2Shape.e_polygonShape)))){ return (DistancePC(x2, x1, (shape2 as b2PolygonShape), xf2, (shape1 as b2CircleShape), xf1)); }; if ((((type1 == b2Shape.e_polygonShape)) && ((type2 == b2Shape.e_polygonShape)))){ return (DistanceGeneric(x1, x2, shape1, xf1, shape2, xf2)); }; if ((((type1 == b2Shape.e_edgeShape)) && ((type2 == b2Shape.e_circleShape)))){ return (DistanceEdgeCircle(x1, x2, (shape1 as b2EdgeShape), xf1, (shape2 as b2CircleShape), xf2)); }; if ((((type1 == b2Shape.e_circleShape)) && ((type2 == b2Shape.e_edgeShape)))){ return (DistanceEdgeCircle(x2, x1, (shape2 as b2EdgeShape), xf2, (shape1 as b2CircleShape), xf1)); }; if ((((type1 == b2Shape.e_polygonShape)) && ((type2 == b2Shape.e_edgeShape)))){ return (DistanceGeneric(x2, x1, shape2, xf2, shape1, xf1)); }; if ((((type1 == b2Shape.e_edgeShape)) && ((type2 == b2Shape.e_polygonShape)))){ return (DistanceGeneric(x1, x2, shape1, xf1, shape2, xf2)); }; return (0); } public static function ProcessTwo(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int{ var p1s_1:b2Vec2; var p2s_0:b2Vec2; var p2s_1:b2Vec2; var lambda:Number; var points_0:b2Vec2 = points[0]; var points_1:b2Vec2 = points[1]; var p1s_0:b2Vec2 = p1s[0]; p1s_1 = p1s[1]; p2s_0 = p2s[0]; p2s_1 = p2s[1]; var rX:Number = -(points_1.x); var rY:Number = -(points_1.y); var dX:Number = (points_0.x - points_1.x); var dY:Number = (points_0.y - points_1.y); var length:Number = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / length); dY = (dY / length); lambda = ((rX * dX) + (rY * dY)); if ((((lambda <= 0)) || ((length < Number.MIN_VALUE)))){ x1.SetV(p1s_1); x2.SetV(p2s_1); p1s_0.SetV(p1s_1); p2s_0.SetV(p2s_1); points_0.SetV(points_1); return (1); }; lambda = (lambda / length); x1.x = (p1s_1.x + (lambda * (p1s_0.x - p1s_1.x))); x1.y = (p1s_1.y + (lambda * (p1s_0.y - p1s_1.y))); x2.x = (p2s_1.x + (lambda * (p2s_0.x - p2s_1.x))); x2.y = (p2s_1.y + (lambda * (p2s_0.y - p2s_1.y))); return (2); } } }//package Box2D.Collision
Section 19
//b2Manifold (Box2D.Collision.b2Manifold) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2Manifold { public var pointCount:int;// = 0 public var normal:b2Vec2; public var points:Array; public function b2Manifold(){ super(); points = new Array(b2Settings.b2_maxManifoldPoints); var i:int; while (i < b2Settings.b2_maxManifoldPoints) { points[i] = new b2ManifoldPoint(); i++; }; normal = new b2Vec2(); } public function Set(m:b2Manifold):void{ pointCount = m.pointCount; var i:int; while (i < b2Settings.b2_maxManifoldPoints) { (points[i] as b2ManifoldPoint).Set(m.points[i]); i++; }; normal.SetV(m.normal); } public function Reset():void{ var i:int; while (i < b2Settings.b2_maxManifoldPoints) { (points[i] as b2ManifoldPoint).Reset(); i++; }; normal.SetZero(); pointCount = 0; } } }//package Box2D.Collision
Section 20
//b2ManifoldPoint (Box2D.Collision.b2ManifoldPoint) package Box2D.Collision { import Box2D.Common.Math.*; public class b2ManifoldPoint { public var separation:Number; public var localPoint2:b2Vec2; public var normalImpulse:Number; public var tangentImpulse:Number; public var localPoint1:b2Vec2; public var id:b2ContactID; public function b2ManifoldPoint(){ localPoint1 = new b2Vec2(); localPoint2 = new b2Vec2(); id = new b2ContactID(); super(); } public function Set(m:b2ManifoldPoint):void{ localPoint1.SetV(m.localPoint1); localPoint2.SetV(m.localPoint2); separation = m.separation; normalImpulse = m.normalImpulse; tangentImpulse = m.tangentImpulse; id.key = m.id.key; } public function Reset():void{ localPoint1.SetZero(); localPoint2.SetZero(); separation = 0; normalImpulse = 0; tangentImpulse = 0; id.key = 0; } } }//package Box2D.Collision
Section 21
//b2OBB (Box2D.Collision.b2OBB) package Box2D.Collision { import Box2D.Common.Math.*; public class b2OBB { public var R:b2Mat22; public var center:b2Vec2; public var extents:b2Vec2; public function b2OBB(){ R = new b2Mat22(); center = new b2Vec2(); extents = new b2Vec2(); super(); } } }//package Box2D.Collision
Section 22
//b2Pair (Box2D.Collision.b2Pair) package Box2D.Collision { public class b2Pair { public var proxy1:b2Proxy; public var proxy2:b2Proxy; public var status:uint; public var userData;// = null public var next:b2Pair; public static var e_pairBuffered:uint = 1; public static var b2_nullProxy:uint = 0xFFFF; public static var e_pairFinal:uint = 4; public static var e_pairRemoved:uint = 2; public function b2Pair(){ super(); } public function SetBuffered():void{ status = (status | e_pairBuffered); } public function IsBuffered():Boolean{ return (((status & e_pairBuffered) == e_pairBuffered)); } public function IsFinal():Boolean{ return (((status & e_pairFinal) == e_pairFinal)); } public function ClearRemoved():void{ status = (status & ~(e_pairRemoved)); } public function SetFinal():void{ status = (status | e_pairFinal); } public function IsRemoved():Boolean{ return (((status & e_pairRemoved) == e_pairRemoved)); } public function ClearBuffered():void{ status = (status & ~(e_pairBuffered)); } public function SetRemoved():void{ status = (status | e_pairRemoved); } } }//package Box2D.Collision
Section 23
//b2PairCallback (Box2D.Collision.b2PairCallback) package Box2D.Collision { public class b2PairCallback { public function b2PairCallback(){ super(); } public function PairRemoved(proxyUserData1, proxyUserData2, pairUserData):void{ } public function PairAdded(proxyUserData1, proxyUserData2){ return (null); } } }//package Box2D.Collision
Section 24
//b2PairManager (Box2D.Collision.b2PairManager) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2PairManager { b2internal var m_pairCount:int; private var m_callback:b2PairCallback; b2internal var m_pairs:Array; private var m_pairBufferCount:int; private var m_broadPhase:b2BroadPhase; private var m_pairBuffer:Array; private var m_freePair:b2Pair; public function b2PairManager(){ super(); m_pairs = new Array(); m_pairBuffer = new Array(); m_pairCount = 0; m_pairBufferCount = 0; m_freePair = null; } public function RemoveBufferedPair(proxy1:b2Proxy, proxy2:b2Proxy):void{ var pair:b2Pair = Find(proxy1, proxy2); if (pair == null){ return; }; if (pair.IsBuffered() == false){ pair.SetBuffered(); m_pairBuffer[m_pairBufferCount] = pair; m_pairBufferCount++; }; pair.SetRemoved(); if (b2BroadPhase.s_validate){ ValidateBuffer(); }; } public function Initialize(broadPhase:b2BroadPhase, callback:b2PairCallback):void{ m_broadPhase = broadPhase; m_callback = callback; } public function Commit():void{ var i:int; var pair:b2Pair; var proxy1:b2Proxy; var proxy2:b2Proxy; var removeCount:int; i = 0; while (i < m_pairBufferCount) { pair = m_pairBuffer[i]; pair.ClearBuffered(); proxy1 = pair.proxy1; proxy2 = pair.proxy2; if (pair.IsRemoved()){ if (pair.IsFinal() == true){ m_callback.PairRemoved(proxy1.userData, proxy2.userData, pair.userData); }; m_pairBuffer[removeCount] = pair; removeCount++; } else { if (pair.IsFinal() == false){ pair.userData = m_callback.PairAdded(proxy1.userData, proxy2.userData); pair.SetFinal(); }; }; i++; }; i = 0; while (i < removeCount) { pair = m_pairBuffer[i]; RemovePair(pair.proxy1, pair.proxy2); i++; }; m_pairBufferCount = 0; if (b2BroadPhase.s_validate){ ValidateTable(); }; } private function ValidateTable():void{ } private function Find(proxy1:b2Proxy, proxy2:b2Proxy):b2Pair{ return (proxy1.pairs[proxy2]); } public function AddBufferedPair(proxy1:b2Proxy, proxy2:b2Proxy):void{ var pair:b2Pair = AddPair(proxy1, proxy2); if (pair.IsBuffered() == false){ pair.SetBuffered(); m_pairBuffer[m_pairBufferCount] = pair; m_pairBufferCount++; }; pair.ClearRemoved(); if (b2BroadPhase.s_validate){ ValidateBuffer(); }; } private function AddPair(proxy1:b2Proxy, proxy2:b2Proxy):b2Pair{ var pair:b2Pair = proxy1.pairs[proxy2]; if (pair != null){ return (pair); }; if (m_freePair == null){ m_freePair = new b2Pair(); m_pairs.push(m_freePair); }; pair = m_freePair; m_freePair = pair.next; pair.proxy1 = proxy1; pair.proxy2 = proxy2; pair.status = 0; pair.userData = null; pair.next = null; proxy1.pairs[proxy2] = pair; proxy2.pairs[proxy1] = pair; m_pairCount++; return (pair); } private function ValidateBuffer():void{ } private function RemovePair(proxy1:b2Proxy, proxy2:b2Proxy){ var pair:b2Pair = proxy1.pairs[proxy2]; if (pair == null){ return (null); }; var userData:* = pair.userData; delete proxy1.pairs[proxy2]; delete proxy2.pairs[proxy1]; pair.next = m_freePair; pair.proxy1 = null; pair.proxy2 = null; pair.userData = null; pair.status = 0; m_freePair = pair; m_pairCount--; return (userData); } } }//package Box2D.Collision
Section 25
//b2Point (Box2D.Collision.b2Point) package Box2D.Collision { import Box2D.Common.Math.*; public class b2Point { public var p:b2Vec2; public function b2Point(){ p = new b2Vec2(); super(); } public function GetFirstVertex(xf:b2XForm):b2Vec2{ return (p); } public function Support(xf:b2XForm, vX:Number, vY:Number):b2Vec2{ return (p); } } }//package Box2D.Collision
Section 26
//b2Proxy (Box2D.Collision.b2Proxy) package Box2D.Collision { import flash.utils.*; public class b2Proxy { public var pairs:Dictionary; public var overlapCount:uint; public var next:b2Proxy; public var userData;// = null public var lowerBounds:Array; public var upperBounds:Array; public var timeStamp:uint; public function b2Proxy(){ lowerBounds = [uint(0), uint(0)]; upperBounds = [uint(0), uint(0)]; pairs = new Dictionary(); super(); } public function IsValid():Boolean{ return (!((overlapCount == b2BroadPhase.b2_invalid))); } } }//package Box2D.Collision
Section 27
//b2Segment (Box2D.Collision.b2Segment) package Box2D.Collision { import Box2D.Common.Math.*; import Box2D.Common.*; public class b2Segment { public var p1:b2Vec2; public var p2:b2Vec2; public function b2Segment(){ p1 = new b2Vec2(); p2 = new b2Vec2(); super(); } public function TestSegment(lambda:Array, normal:b2Vec2, segment:b2Segment, maxLambda:Number):Boolean{ var bX:Number; var bY:Number; var a:Number; var mu2:Number; var nLen:Number; var s:b2Vec2 = segment.p1; var rX:Number = (segment.p2.x - s.x); var rY:Number = (segment.p2.y - s.y); var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); var nX:Number = dY; var nY:Number = -(dX); var k_slop:Number = (100 * Number.MIN_VALUE); var denom:Number = -(((rX * nX) + (rY * nY))); if (denom > k_slop){ bX = (s.x - p1.x); bY = (s.y - p1.y); a = ((bX * nX) + (bY * nY)); if ((((0 <= a)) && ((a <= (maxLambda * denom))))){ mu2 = ((-(rX) * bY) + (rY * bX)); if (((((-(k_slop) * denom) <= mu2)) && ((mu2 <= (denom * (1 + k_slop)))))){ a = (a / denom); nLen = Math.sqrt(((nX * nX) + (nY * nY))); nX = (nX / nLen); nY = (nY / nLen); lambda[0] = a; normal.Set(nX, nY); return (true); }; }; }; return (false); } public function Extend(aabb:b2AABB):void{ ExtendForward(aabb); ExtendBackward(aabb); } public function ExtendForward(aabb:b2AABB):void{ var lambda:Number; var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); lambda = Math.min(((dX > 0)) ? ((aabb.upperBound.x - p1.x) / dX) : ((dX < 0)) ? ((aabb.lowerBound.x - p1.x) / dX) : Number.POSITIVE_INFINITY, ((dY > 0)) ? ((aabb.upperBound.y - p1.y) / dY) : ((dY < 0)) ? ((aabb.lowerBound.y - p1.y) / dY) : Number.POSITIVE_INFINITY); p2.x = (p1.x + (dX * lambda)); p2.y = (p1.y + (dY * lambda)); } public function ExtendBackward(aabb:b2AABB):void{ var lambda:Number; var dX:Number = (-(p2.x) + p1.x); var dY:Number = (-(p2.y) + p1.y); lambda = Math.min(((dX > 0)) ? ((aabb.upperBound.x - p2.x) / dX) : ((dX < 0)) ? ((aabb.lowerBound.x - p2.x) / dX) : Number.POSITIVE_INFINITY, ((dY > 0)) ? ((aabb.upperBound.y - p2.y) / dY) : ((dY < 0)) ? ((aabb.lowerBound.y - p2.y) / dY) : Number.POSITIVE_INFINITY); p1.x = (p2.x + (dX * lambda)); p1.y = (p2.y + (dY * lambda)); } } }//package Box2D.Collision
Section 28
//b2TimeOfImpact (Box2D.Collision.b2TimeOfImpact) package Box2D.Collision { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Common.*; public class b2TimeOfImpact { public static var s_xf1:b2XForm = new b2XForm(); public static var s_xf2:b2XForm = new b2XForm(); public static var s_p1:b2Vec2 = new b2Vec2(); public static var s_p2:b2Vec2 = new b2Vec2(); public function b2TimeOfImpact(){ super(); } public static function TimeOfImpact(shape1:b2Shape, sweep1:b2Sweep, shape2:b2Shape, sweep2:b2Sweep):Number{ var math1:Number; var math2:Number; var t:Number; var xf1:b2XForm; var xf2:b2XForm; var nLen:Number; var approachVelocityBound:Number; var dAlpha:Number; var newAlpha:Number; var r1:Number = shape1.m_sweepRadius; var r2:Number = shape2.m_sweepRadius; var t0:Number = sweep1.t0; var v1X:Number = (sweep1.c.x - sweep1.c0.x); var v1Y:Number = (sweep1.c.y - sweep1.c0.y); var v2X:Number = (sweep2.c.x - sweep2.c0.x); var v2Y:Number = (sweep2.c.y - sweep2.c0.y); var omega1:Number = (sweep1.a - sweep1.a0); var omega2:Number = (sweep2.a - sweep2.a0); var alpha:Number = 0; var p1:b2Vec2 = s_p1; var p2:b2Vec2 = s_p2; var k_maxIterations = 20; var iter:int; var normalX:Number = 0; var normalY:Number = 0; var distance:Number = 0; var targetDistance:Number = 0; while (true) { t = (((1 - alpha) * t0) + alpha); xf1 = s_xf1; xf2 = s_xf2; sweep1.GetXForm(xf1, t); sweep2.GetXForm(xf2, t); distance = b2Distance.Distance(p1, p2, shape1, xf1, shape2, xf2); if (iter == 0){ if (distance > (2 * b2Settings.b2_toiSlop)){ targetDistance = (1.5 * b2Settings.b2_toiSlop); } else { math1 = (0.05 * b2Settings.b2_toiSlop); math2 = (distance - (0.5 * b2Settings.b2_toiSlop)); targetDistance = ((math1 > math2)) ? math1 : math2; }; }; if (((((distance - targetDistance) < (0.05 * b2Settings.b2_toiSlop))) || ((iter == k_maxIterations)))){ break; }; normalX = (p2.x - p1.x); normalY = (p2.y - p1.y); nLen = Math.sqrt(((normalX * normalX) + (normalY * normalY))); normalX = (normalX / nLen); normalY = (normalY / nLen); approachVelocityBound = ((((normalX * (v1X - v2X)) + (normalY * (v1Y - v2Y))) + (((omega1 < 0)) ? -(omega1) : omega1 * r1)) + (((omega2 < 0)) ? -(omega2) : omega2 * r2)); if (approachVelocityBound == 0){ alpha = 1; break; }; dAlpha = ((distance - targetDistance) / approachVelocityBound); newAlpha = (alpha + dAlpha); if ((((newAlpha < 0)) || ((1 < newAlpha)))){ alpha = 1; break; }; if (newAlpha < ((1 + (100 * Number.MIN_VALUE)) * alpha)){ break; }; alpha = newAlpha; iter++; }; return (alpha); } } }//package Box2D.Collision
Section 29
//ClipVertex (Box2D.Collision.ClipVertex) package Box2D.Collision { import Box2D.Common.Math.*; public class ClipVertex { public var id:b2ContactID; public var v:b2Vec2; public function ClipVertex(){ v = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Collision
Section 30
//Features (Box2D.Collision.Features) package Box2D.Collision { import Box2D.Common.*; public class Features { b2internal var _referenceEdge:int; b2internal var _incidentEdge:int; b2internal var _flip:int; b2internal var _incidentVertex:int; b2internal var _m_id:b2ContactID; public function Features(){ super(); } public function get referenceEdge():int{ return (_referenceEdge); } public function set incidentVertex(value:int):void{ _incidentVertex = value; _m_id._key = ((_m_id._key & 4278255615) | ((_incidentVertex << 16) & 0xFF0000)); } public function get flip():int{ return (_flip); } public function get incidentEdge():int{ return (_incidentEdge); } public function set referenceEdge(value:int):void{ _referenceEdge = value; _m_id._key = ((_m_id._key & 4294967040) | (_referenceEdge & 0xFF)); } public function get incidentVertex():int{ return (_incidentVertex); } public function set flip(value:int):void{ _flip = value; _m_id._key = ((_m_id._key & 0xFFFFFF) | ((_flip << 24) & 4278190080)); } public function set incidentEdge(value:int):void{ _incidentEdge = value; _m_id._key = ((_m_id._key & 4294902015) | ((_incidentEdge << 8) & 0xFF00)); } } }//package Box2D.Collision
Section 31
//b2Mat22 (Box2D.Common.Math.b2Mat22) package Box2D.Common.Math { public class b2Mat22 { public var col1:b2Vec2; public var col2:b2Vec2; public function b2Mat22(angle:Number=0, c1:b2Vec2=null, c2:b2Vec2=null){ var c:Number; var s:Number; col1 = new b2Vec2(); col2 = new b2Vec2(); super(); if (((!((c1 == null))) && (!((c2 == null))))){ col1.SetV(c1); col2.SetV(c2); } else { c = Math.cos(angle); s = Math.sin(angle); col1.x = c; col2.x = -(s); col1.y = s; col2.y = c; }; } public function SetIdentity():void{ col1.x = 1; col2.x = 0; col1.y = 0; col2.y = 1; } public function SetVV(c1:b2Vec2, c2:b2Vec2):void{ col1.SetV(c1); col2.SetV(c2); } public function Set(angle:Number):void{ var c:Number; c = Math.cos(angle); var s:Number = Math.sin(angle); col1.x = c; col2.x = -(s); col1.y = s; col2.y = c; } public function SetZero():void{ col1.x = 0; col2.x = 0; col1.y = 0; col2.y = 0; } public function SetM(m:b2Mat22):void{ col1.SetV(m.col1); col2.SetV(m.col2); } public function AddM(m:b2Mat22):void{ col1.x = (col1.x + m.col1.x); col1.y = (col1.y + m.col1.y); col2.x = (col2.x + m.col2.x); col2.y = (col2.y + m.col2.y); } public function Abs():void{ col1.Abs(); col2.Abs(); } public function Copy():b2Mat22{ return (new b2Mat22(0, col1, col2)); } public function GetInverse(out:b2Mat22):b2Mat22{ var a:Number; var c:Number; var det:Number; a = col1.x; var b:Number = col2.x; c = col1.y; var d:Number = col2.y; det = ((a * d) - (b * c)); det = (1 / det); out.col1.x = (det * d); out.col2.x = (-(det) * b); out.col1.y = (-(det) * c); out.col2.y = (det * a); return (out); } public function GetAngle():Number{ return (Math.atan2(col1.y, col1.x)); } public function Solve(out:b2Vec2, bX:Number, bY:Number):b2Vec2{ var a11:Number = col1.x; var a12:Number = col2.x; var a21:Number = col1.y; var a22:Number = col2.y; var det:Number = ((a11 * a22) - (a12 * a21)); det = (1 / det); out.x = (det * ((a22 * bX) - (a12 * bY))); out.y = (det * ((a11 * bY) - (a21 * bX))); return (out); } } }//package Box2D.Common.Math
Section 32
//b2Mat33 (Box2D.Common.Math.b2Mat33) package Box2D.Common.Math { public class b2Mat33 { public var col1:b2Vec3; public var col2:b2Vec3; public var col3:b2Vec3; public function b2Mat33(c1:b2Vec3=null, c2:b2Vec3=null, c3:b2Vec3=null){ col1 = new b2Vec3(); col2 = new b2Vec3(); col3 = new b2Vec3(); super(); if (((((!(c1)) && (!(c2)))) && (!(c3)))){ col1.SetZero(); col2.SetZero(); col3.SetZero(); } else { col1.SetV(c1); col2.SetV(c2); col3.SetV(c3); }; } public function SetIdentity():void{ col1.x = 1; col2.x = 0; col3.x = 0; col1.y = 0; col2.y = 1; col3.y = 0; col1.z = 0; col2.z = 0; col3.z = 1; } public function Solve22(out:b2Vec2, bX:Number, bY:Number):b2Vec2{ var a11:Number; a11 = col1.x; var a12:Number = col2.x; var a21:Number = col1.y; var a22:Number = col2.y; var det:Number = ((a11 * a22) - (a12 * a21)); det = (1 / det); out.x = (det * ((a22 * bX) - (a12 * bY))); out.y = (det * ((a11 * bY) - (a21 * bX))); return (out); } public function SetZero():void{ col1.x = 0; col2.x = 0; col3.x = 0; col1.y = 0; col2.y = 0; col3.y = 0; col1.z = 0; col2.z = 0; col3.z = 0; } public function SetM(m:b2Mat33):void{ col1.SetV(m.col1); col2.SetV(m.col2); col3.SetV(m.col3); } public function AddM(m:b2Mat33):void{ col1.x = (col1.x + m.col1.x); col1.y = (col1.y + m.col1.y); col1.z = (col1.z + m.col1.z); col2.x = (col2.x + m.col2.x); col2.y = (col2.y + m.col2.y); col2.z = (col2.z + m.col2.z); col3.x = (col3.x + m.col3.x); col3.y = (col3.y + m.col3.y); col3.z = (col3.z + m.col3.z); } public function SetVVV(c1:b2Vec3, c2:b2Vec3, c3:b2Vec3):void{ col1.SetV(c1); col2.SetV(c2); col3.SetV(c3); } public function Copy():b2Mat33{ return (new b2Mat33(col1, col2, col3)); } public function Solve33(out:b2Vec3, bX:Number, bY:Number, bZ:Number):b2Vec3{ var a11:Number = col1.x; var a21:Number = col1.y; var a31:Number = col1.z; var a12:Number = col2.x; var a22:Number = col2.y; var a32:Number = col2.z; var a13:Number = col3.x; var a23:Number = col3.y; var a33:Number = col3.z; var det:Number = (((a11 * ((a22 * a33) - (a32 * a23))) + (a21 * ((a32 * a13) - (a12 * a33)))) + (a31 * ((a12 * a23) - (a22 * a13)))); det = (1 / det); out.x = (det * (((bX * ((a22 * a33) - (a32 * a23))) + (bY * ((a32 * a13) - (a12 * a33)))) + (bZ * ((a12 * a23) - (a22 * a13))))); out.y = (det * (((a11 * ((bY * a33) - (bZ * a23))) + (a21 * ((bZ * a13) - (bX * a33)))) + (a31 * ((bX * a23) - (bY * a13))))); out.z = (det * (((a11 * ((a22 * bZ) - (a32 * bY))) + (a21 * ((a32 * bX) - (a12 * bZ)))) + (a31 * ((a12 * bY) - (a22 * bX))))); return (out); } } }//package Box2D.Common.Math
Section 33
//b2Math (Box2D.Common.Math.b2Math) package Box2D.Common.Math { public class b2Math { public static const b2Mat22_identity:b2Mat22 = new b2Mat22(0, new b2Vec2(1, 0), new b2Vec2(0, 1)); public static const b2XForm_identity:b2XForm = new b2XForm(b2Vec2_zero, b2Mat22_identity); public static const b2Vec2_zero:b2Vec2 = new b2Vec2(0, 0); public function b2Math(){ super(); } public static function b2CrossVF(a:b2Vec2, s:Number):b2Vec2{ var v:b2Vec2 = new b2Vec2((s * a.y), (-(s) * a.x)); return (v); } public static function AddVV(a:b2Vec2, b:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((a.x + b.x), (a.y + b.y)); return (v); } public static function b2IsValid(x:Number):Boolean{ return (isFinite(x)); } public static function b2MinV(a:b2Vec2, b:b2Vec2):b2Vec2{ var c:b2Vec2 = new b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); return (c); } public static function b2MulX(T:b2XForm, v:b2Vec2):b2Vec2{ var a:b2Vec2; a = b2MulMV(T.R, v); a.x = (a.x + T.position.x); a.y = (a.y + T.position.y); return (a); } public static function b2DistanceSquared(a:b2Vec2, b:b2Vec2):Number{ var cX:Number = (a.x - b.x); var cY:Number = (a.y - b.y); return (((cX * cX) + (cY * cY))); } public static function b2Swap(a:Array, b:Array):void{ var tmp:* = a[0]; a[0] = b[0]; b[0] = tmp; } public static function b2AbsM(A:b2Mat22):b2Mat22{ var B:b2Mat22 = new b2Mat22(0, b2AbsV(A.col1), b2AbsV(A.col2)); return (B); } public static function SubtractVV(a:b2Vec2, b:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((a.x - b.x), (a.y - b.y)); return (v); } public static function b2MulXT(T:b2XForm, v:b2Vec2):b2Vec2{ var a:b2Vec2; var tX:Number; a = SubtractVV(v, T.position); tX = ((a.x * T.R.col1.x) + (a.y * T.R.col1.y)); a.y = ((a.x * T.R.col2.x) + (a.y * T.R.col2.y)); a.x = tX; return (a); } public static function b2Abs(a:Number):Number{ return (((a > 0)) ? a : -(a)); } public static function b2Clamp(a:Number, low:Number, high:Number):Number{ return (b2Max(low, b2Min(a, high))); } public static function b2AbsV(a:b2Vec2):b2Vec2{ var b:b2Vec2 = new b2Vec2(b2Abs(a.x), b2Abs(a.y)); return (b); } public static function MulFV(s:Number, a:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((s * a.x), (s * a.y)); return (v); } public static function b2CrossVV(a:b2Vec2, b:b2Vec2):Number{ return (((a.x * b.y) - (a.y * b.x))); } public static function b2Dot(a:b2Vec2, b:b2Vec2):Number{ return (((a.x * b.x) + (a.y * b.y))); } public static function b2CrossFV(s:Number, a:b2Vec2):b2Vec2{ var v:b2Vec2 = new b2Vec2((-(s) * a.y), (s * a.x)); return (v); } public static function AddMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var C:b2Mat22 = new b2Mat22(0, AddVV(A.col1, B.col1), AddVV(A.col2, B.col2)); return (C); } public static function b2Distance(a:b2Vec2, b:b2Vec2):Number{ var cX:Number = (a.x - b.x); var cY:Number = (a.y - b.y); return (Math.sqrt(((cX * cX) + (cY * cY)))); } public static function b2MulTMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var c1:b2Vec2 = new b2Vec2(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1)); var c2:b2Vec2 = new b2Vec2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2)); var C:b2Mat22 = new b2Mat22(0, c1, c2); return (C); } public static function b2MaxV(a:b2Vec2, b:b2Vec2):b2Vec2{ var c:b2Vec2 = new b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); return (c); } public static function b2IsPowerOfTwo(x:uint):Boolean{ var result:Boolean = (((x > 0)) && (((x & (x - 1)) == 0))); return (result); } public static function b2ClampV(a:b2Vec2, low:b2Vec2, high:b2Vec2):b2Vec2{ return (b2MaxV(low, b2MinV(a, high))); } public static function b2RandomRange(lo:Number, hi:Number):Number{ var r:Number = Math.random(); r = (((hi - lo) * r) + lo); return (r); } public static function b2MulTMV(A:b2Mat22, v:b2Vec2):b2Vec2{ var u:b2Vec2 = new b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2)); return (u); } public static function b2Min(a:Number, b:Number):Number{ return (((a < b)) ? a : b); } public static function b2Random():Number{ return (((Math.random() * 2) - 1)); } public static function b2MulMM(A:b2Mat22, B:b2Mat22):b2Mat22{ var C:b2Mat22 = new b2Mat22(0, b2MulMV(A, B.col1), b2MulMV(A, B.col2)); return (C); } public static function b2NextPowerOfTwo(x:uint):uint{ x = (x | ((x >> 1) & 2147483647)); x = (x | ((x >> 2) & 1073741823)); x = (x | ((x >> 4) & 268435455)); x = (x | ((x >> 8) & 0xFFFFFF)); x = (x | ((x >> 16) & 0xFFFF)); return ((x + 1)); } public static function b2Max(a:Number, b:Number):Number{ return (((a > b)) ? a : b); } public static function b2MulMV(A:b2Mat22, v:b2Vec2):b2Vec2{ var u:b2Vec2 = new b2Vec2(((A.col1.x * v.x) + (A.col2.x * v.y)), ((A.col1.y * v.x) + (A.col2.y * v.y))); return (u); } } }//package Box2D.Common.Math
Section 34
//b2Sweep (Box2D.Common.Math.b2Sweep) package Box2D.Common.Math { public class b2Sweep { public var localCenter:b2Vec2; public var a:Number; public var c:b2Vec2; public var a0:Number; public var c0:b2Vec2; public var t0:Number; public function b2Sweep(){ localCenter = new b2Vec2(); c0 = new b2Vec2(); c = new b2Vec2(); super(); } public function Advance(t:Number):void{ var alpha:Number; if ((((t0 < t)) && (((1 - t0) > Number.MIN_VALUE)))){ alpha = ((t - t0) / (1 - t0)); c0.x = (((1 - alpha) * c0.x) + (alpha * c.x)); c0.y = (((1 - alpha) * c0.y) + (alpha * c.y)); a0 = (((1 - alpha) * a0) + (alpha * a)); t0 = t; }; } public function GetXForm(xf:b2XForm, t:Number):void{ var alpha:Number; var angle:Number; if ((1 - t0) > Number.MIN_VALUE){ alpha = ((t - t0) / (1 - t0)); xf.position.x = (((1 - alpha) * c0.x) + (alpha * c.x)); xf.position.y = (((1 - alpha) * c0.y) + (alpha * c.y)); angle = (((1 - alpha) * a0) + (alpha * a)); xf.R.Set(angle); } else { xf.position.SetV(c); xf.R.Set(a); }; var tMat:b2Mat22 = xf.R; xf.position.x = (xf.position.x - ((tMat.col1.x * localCenter.x) + (tMat.col2.x * localCenter.y))); xf.position.y = (xf.position.y - ((tMat.col1.y * localCenter.x) + (tMat.col2.y * localCenter.y))); } } }//package Box2D.Common.Math
Section 35
//b2Vec2 (Box2D.Common.Math.b2Vec2) package Box2D.Common.Math { public class b2Vec2 { public var y:Number; public var x:Number; public function b2Vec2(x_:Number=0, y_:Number=0):void{ super(); x = x_; y = y_; } public function Add(v:b2Vec2):void{ x = (x + v.x); y = (y + v.y); } public function Set(x_:Number=0, y_:Number=0):void{ x = x_; y = y_; } public function Multiply(a:Number):void{ x = (x * a); y = (y * a); } public function Length():Number{ return (Math.sqrt(((x * x) + (y * y)))); } public function LengthSquared():Number{ return (((x * x) + (y * y))); } public function MulM(A:b2Mat22):void{ var tX:Number = x; x = ((A.col1.x * tX) + (A.col2.x * y)); y = ((A.col1.y * tX) + (A.col2.y * y)); } public function SetZero():void{ x = 0; y = 0; } public function MinV(b:b2Vec2):void{ x = ((x < b.x)) ? x : b.x; y = ((y < b.y)) ? y : b.y; } public function Normalize():Number{ var length:Number = Math.sqrt(((x * x) + (y * y))); if (length < Number.MIN_VALUE){ return (0); }; var invLength:Number = (1 / length); x = (x * invLength); y = (y * invLength); return (length); } public function CrossVF(s:Number):void{ var tX:Number = x; x = (s * y); y = (-(s) * tX); } public function MaxV(b:b2Vec2):void{ x = ((x > b.x)) ? x : b.x; y = ((y > b.y)) ? y : b.y; } public function SetV(v:b2Vec2):void{ x = v.x; y = v.y; } public function Negative():b2Vec2{ return (new b2Vec2(-(x), -(y))); } public function CrossFV(s:Number):void{ var tX:Number = x; x = (-(s) * y); y = (s * tX); } public function Abs():void{ if (x < 0){ x = -(x); }; if (y < 0){ y = -(y); }; } public function Subtract(v:b2Vec2):void{ x = (x - v.x); y = (y - v.y); } public function Copy():b2Vec2{ return (new b2Vec2(x, y)); } public function MulTM(A:b2Mat22):void{ var tX:Number = b2Math.b2Dot(this, A.col1); y = b2Math.b2Dot(this, A.col2); x = tX; } public function IsValid():Boolean{ return (((b2Math.b2IsValid(x)) && (b2Math.b2IsValid(y)))); } public static function Make(x_:Number, y_:Number):b2Vec2{ return (new b2Vec2(x_, y_)); } } }//package Box2D.Common.Math
Section 36
//b2Vec3 (Box2D.Common.Math.b2Vec3) package Box2D.Common.Math { public class b2Vec3 { public var x:Number; public var y:Number; public var z:Number; public function b2Vec3(x:Number=0, y:Number=0, z:Number=0){ super(); this.x = x; this.y = y; this.z = z; } public function Add(v:b2Vec3):void{ x = (x + v.x); y = (y + v.y); z = (z + v.z); } public function Set(x:Number, y:Number, z:Number):void{ this.x = x; this.y = y; this.z = z; } public function Multiply(a:Number):void{ x = (x * a); y = (y * a); z = (z * a); } public function SetZero():void{ x = (y = (z = 0)); } public function SetV(v:b2Vec3):void{ x = v.x; y = v.y; z = v.z; } public function Negative():b2Vec3{ return (new b2Vec3(-(x), -(y), -(z))); } public function Subtract(v:b2Vec3):void{ x = (x - v.x); y = (y - v.y); z = (z - v.z); } public function Copy():b2Vec3{ return (new b2Vec3(x, y, z)); } } }//package Box2D.Common.Math
Section 37
//b2XForm (Box2D.Common.Math.b2XForm) package Box2D.Common.Math { public class b2XForm { public var position:b2Vec2; public var R:b2Mat22; public function b2XForm(pos:b2Vec2=null, r:b2Mat22=null):void{ position = new b2Vec2(); R = new b2Mat22(); super(); if (pos){ position.SetV(pos); R.SetM(r); }; } public function Initialize(pos:b2Vec2, r:b2Mat22):void{ position.SetV(pos); R.SetM(r); } public function Set(x:b2XForm):void{ position.SetV(x.position); R.SetM(x.R); } public function SetIdentity():void{ position.SetZero(); R.SetIdentity(); } } }//package Box2D.Common.Math
Section 38
//b2Color (Box2D.Common.b2Color) package Box2D.Common { import Box2D.Common.Math.*; public class b2Color { private var _r:uint;// = 0 private var _g:uint;// = 0 private var _b:uint;// = 0 public function b2Color(rr:Number, gg:Number, bb:Number){ super(); _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function Set(rr:Number, gg:Number, bb:Number):void{ _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function set b(bb:Number):void{ _b = uint((0xFF * b2Math.b2Clamp(bb, 0, 1))); } public function get color():uint{ return ((((_r << 16) | (_g << 8)) | _b)); } public function set r(rr:Number):void{ _r = uint((0xFF * b2Math.b2Clamp(rr, 0, 1))); } public function set g(gg:Number):void{ _g = uint((0xFF * b2Math.b2Clamp(gg, 0, 1))); } } }//package Box2D.Common
Section 39
//b2internal (Box2D.Common.b2internal) package Box2D.Common { public namespace b2internal = "http://www.box2d.org/ns/b2internal"; }//package Box2D.Common
Section 40
//b2Settings (Box2D.Common.b2Settings) package Box2D.Common { import Box2D.Common.Math.*; public class b2Settings { public static const b2_maxLinearVelocity:Number = 200; public static const b2_pi:Number = 3.14159265358979; public static const b2_angularSleepTolerance:Number = 0.0111111111111111; public static const b2_linearSleepTolerance:Number = 0.01; public static const b2_angularSlop:Number = 0.0349065850398866; public static const b2_linearSlop:Number = 0.005; public static const b2_maxLinearVelocitySquared:Number = 40000; public static const b2_maxTOIJointsPerIsland:int = 32; public static const b2_maxAngularVelocitySquared:Number = 62500; public static const b2_maxPolygonVertices:int = 8; public static const b2_velocityThreshold:Number = 1; public static const b2_contactBaumgarte:Number = 0.2; public static const b2_maxTOIContactsPerIsland:int = 32; public static const b2_maxManifoldPoints:int = 2; public static const b2_maxAngularVelocity:Number = 250; public static const b2_maxAngularCorrection:Number = 0.139626340159546; public static const b2_timeToSleep:Number = 0.5; public static const USHRT_MAX:int = 0xFFFF; public static const b2_maxLinearCorrection:Number = 0.2; public static const b2_toiSlop:Number = 0.04; public static const VERSION:String = "2.0.2"; public function b2Settings(){ super(); } public static function b2MixFriction(friction1:Number, friction2:Number):Number{ return (Math.sqrt((friction1 * friction2))); } public static function b2MixRestitution(restitution1:Number, restitution2:Number):Number{ return (((restitution1 > restitution2)) ? restitution1 : restitution2); } public static function b2Assert(a:Boolean):void{ var nullVec:b2Vec2; if (!a){ nullVec.x++; }; } } }//package Box2D.Common
Section 41
//b2CircleContact (Box2D.Dynamics.Contacts.b2CircleContact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2CircleContact extends b2Contact { private var m_manifolds:Array; private var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2CircleContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; m_manifold.pointCount = 0; var point:b2ManifoldPoint = m_manifold.points[0]; point.normalImpulse = 0; point.tangentImpulse = 0; } override b2internal function Evaluate(listener:b2ContactListener):void{ var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollideCircles(m_manifold, (m_shape1 as b2CircleShape), b1.m_xf, (m_shape2 as b2CircleShape), b2.m_xf); var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = b2Settings.b2MixFriction(m_shape1.GetFriction(), m_shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(m_shape1.GetRestitution(), m_shape2.GetRestitution()); if (m_manifold.pointCount > 0){ m_manifoldCount = 1; mp = m_manifold.points[0]; if (m0.pointCount == 0){ mp.normalImpulse = 0; mp.tangentImpulse = 0; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Add(cp); }; } else { mp0 = m0.points[0]; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Persist(cp); }; }; } else { m_manifoldCount = 0; if ((((m0.pointCount > 0)) && (listener))){ mp0 = m0.points[0]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2CircleContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 42
//b2Contact (Box2D.Dynamics.Contacts.b2Contact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2Contact { b2internal var m_shape1:b2Shape; b2internal var m_shape2:b2Shape; b2internal var m_prev:b2Contact; b2internal var m_toi:Number; b2internal var m_next:b2Contact; b2internal var m_manifoldCount:int; b2internal var m_node1:b2ContactEdge; b2internal var m_node2:b2ContactEdge; b2internal var m_flags:uint; b2internal static var e_toiFlag:uint = 8; b2internal static var e_nonSolidFlag:uint = 1; b2internal static var e_slowFlag:uint = 2; b2internal static var e_islandFlag:uint = 4; b2internal static var s_registers:Array; b2internal static var s_initialized:Boolean = false; public function b2Contact(s1:b2Shape=null, s2:b2Shape=null){ m_node1 = new b2ContactEdge(); m_node2 = new b2ContactEdge(); super(); m_flags = 0; if (((!(s1)) || (!(s2)))){ m_shape1 = null; m_shape2 = null; return; }; if (((s1.IsSensor()) || (s2.IsSensor()))){ m_flags = (m_flags | e_nonSolidFlag); }; m_shape1 = s1; m_shape2 = s2; m_manifoldCount = 0; m_prev = null; m_next = null; m_node1.contact = null; m_node1.prev = null; m_node1.next = null; m_node1.other = null; m_node2.contact = null; m_node2.prev = null; m_node2.next = null; m_node2.other = null; } public function IsSolid():Boolean{ return (((m_flags & e_nonSolidFlag) == 0)); } public function GetShape1():b2Shape{ return (m_shape1); } public function GetShape2():b2Shape{ return (m_shape2); } public function GetNext():b2Contact{ return (m_next); } public function GetManifoldCount():int{ return (m_manifoldCount); } public function GetManifolds():Array{ return (null); } b2internal function Update(listener:b2ContactListener):void{ var oldCount:int = m_manifoldCount; Evaluate(listener); var newCount:int = m_manifoldCount; var body1:b2Body = m_shape1.m_body; var body2:b2Body = m_shape2.m_body; if ((((newCount == 0)) && ((oldCount > 0)))){ body1.WakeUp(); body2.WakeUp(); }; if (((((((body1.IsStatic()) || (body1.IsBullet()))) || (body2.IsStatic()))) || (body2.IsBullet()))){ m_flags = (m_flags & ~(e_slowFlag)); } else { m_flags = (m_flags | e_slowFlag); }; } b2internal function Evaluate(listener:b2ContactListener):void{ } b2internal static function InitializeRegisters():void{ var j:int; s_registers = new Array(b2Shape.e_shapeTypeCount); var i:int; while (i < b2Shape.e_shapeTypeCount) { s_registers[i] = new Array(b2Shape.e_shapeTypeCount); j = 0; while (j < b2Shape.e_shapeTypeCount) { s_registers[i][j] = new b2ContactRegister(); j++; }; i++; }; AddType(b2CircleContact.Create, b2CircleContact.Destroy, b2Shape.e_circleShape, b2Shape.e_circleShape); AddType(b2PolyAndCircleContact.Create, b2PolyAndCircleContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_circleShape); AddType(b2PolygonContact.Create, b2PolygonContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_polygonShape); AddType(b2EdgeAndCircleContact.Create, b2EdgeAndCircleContact.Destroy, b2Shape.e_edgeShape, b2Shape.e_circleShape); AddType(b2PolyAndEdgeContact.Create, b2PolyAndEdgeContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_edgeShape); } b2internal static function Destroy(contact:b2Contact, allocator):void{ if (contact.m_manifoldCount > 0){ contact.m_shape1.m_body.WakeUp(); contact.m_shape2.m_body.WakeUp(); }; var type1:int = contact.m_shape1.m_type; var type2:int = contact.m_shape2.m_type; var reg:b2ContactRegister = s_registers[type1][type2]; var destroyFcn:Function = reg.destroyFcn; destroyFcn(contact, allocator); } b2internal static function AddType(createFcn:Function, destroyFcn:Function, type1:int, type2:int):void{ s_registers[type1][type2].createFcn = createFcn; s_registers[type1][type2].destroyFcn = destroyFcn; s_registers[type1][type2].primary = true; if (type1 != type2){ s_registers[type2][type1].createFcn = createFcn; s_registers[type2][type1].destroyFcn = destroyFcn; s_registers[type2][type1].primary = false; }; } b2internal static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ var c:b2Contact; var i:int; var m:b2Manifold; if (s_initialized == false){ InitializeRegisters(); s_initialized = true; }; var type1:int = shape1.m_type; var type2:int = shape2.m_type; var reg:b2ContactRegister = s_registers[type1][type2]; var createFcn:Function = reg.createFcn; if (createFcn != null){ if (reg.primary){ return (createFcn(shape1, shape2, allocator)); }; c = createFcn(shape2, shape1, allocator); i = 0; while (i < c.m_manifoldCount) { m = c.GetManifolds()[i]; m.normal = m.normal.Negative(); i++; }; return (c); //unresolved jump }; return (null); } } }//package Box2D.Dynamics.Contacts
Section 43
//b2ContactConstraint (Box2D.Dynamics.Contacts.b2ContactConstraint) package Box2D.Dynamics.Contacts { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2ContactConstraint { public var points:Array; public var normal:b2Vec2; public var restitution:Number; public var K:b2Mat22; public var body1:b2Body; public var manifold:b2Manifold; public var body2:b2Body; public var friction:Number; public var normalMass:b2Mat22; public var pointCount:int; public function b2ContactConstraint(){ normal = new b2Vec2(); normalMass = new b2Mat22(); K = new b2Mat22(); super(); points = new Array(b2Settings.b2_maxManifoldPoints); var i:int; while (i < b2Settings.b2_maxManifoldPoints) { points[i] = new b2ContactConstraintPoint(); i++; }; } } }//package Box2D.Dynamics.Contacts
Section 44
//b2ContactConstraintPoint (Box2D.Dynamics.Contacts.b2ContactConstraintPoint) package Box2D.Dynamics.Contacts { import Box2D.Common.Math.*; public class b2ContactConstraintPoint { public var r2:b2Vec2; public var separation:Number; public var normalImpulse:Number; public var tangentImpulse:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var equalizedMass:Number; public var tangentMass:Number; public var normalMass:Number; public var velocityBias:Number; public var r1:b2Vec2; public function b2ContactConstraintPoint(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); r1 = new b2Vec2(); r2 = new b2Vec2(); super(); } } }//package Box2D.Dynamics.Contacts
Section 45
//b2ContactEdge (Box2D.Dynamics.Contacts.b2ContactEdge) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; public class b2ContactEdge { public var other:b2Body; public var prev:b2ContactEdge; public var contact:b2Contact; public var next:b2ContactEdge; public function b2ContactEdge(){ super(); } } }//package Box2D.Dynamics.Contacts
Section 46
//b2ContactRegister (Box2D.Dynamics.Contacts.b2ContactRegister) package Box2D.Dynamics.Contacts { public class b2ContactRegister { public var primary:Boolean; public var createFcn:Function; public var destroyFcn:Function; public function b2ContactRegister(){ super(); } } }//package Box2D.Dynamics.Contacts
Section 47
//b2ContactResult (Box2D.Dynamics.Contacts.b2ContactResult) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Collision.*; public class b2ContactResult { public var position:b2Vec2; public var shape1:b2Shape; public var shape2:b2Shape; public var normalImpulse:Number; public var normal:b2Vec2; public var tangentImpulse:Number; public var id:b2ContactID; public function b2ContactResult(){ position = new b2Vec2(); normal = new b2Vec2(); id = new b2ContactID(); super(); } } }//package Box2D.Dynamics.Contacts
Section 48
//b2ContactSolver (Box2D.Dynamics.Contacts.b2ContactSolver) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2ContactSolver { private var m_constraintCount:int; b2internal var m_constraints:Array; private var m_allocator; private var m_step:b2TimeStep; public function b2ContactSolver(step:b2TimeStep, contacts:Array, contactCount:int, allocator){ var contact:b2Contact; var i:int; var tVec:b2Vec2; var tMat:b2Mat22; var shape1:b2Shape; var shape2:b2Shape; var b1:b2Body; var b2:b2Body; var manifoldCount:int; var manifolds:Array; var friction:Number; var restitution:Number; var v1X:Number; var v1Y:Number; var v2X:Number; var v2Y:Number; var w1:Number; var w2:Number; var j:int; var manifold:b2Manifold; var normalX:Number; var normalY:Number; var cc:b2ContactConstraint; var k:uint; var cp:b2ManifoldPoint; var ccp:b2ContactConstraintPoint; var tX:Number; var tY:Number; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var rn1:Number; var rn2:Number; var kNormal:Number; var kEqualized:Number; var tangentX:Number; var tangentY:Number; var rt1:Number; var rt2:Number; var kTangent:Number; var vRel:Number; var ccp1:b2ContactConstraintPoint; var ccp2:b2ContactConstraintPoint; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var rn11:Number; var rn12:Number; var rn21:Number; var rn22:Number; var k11:Number; var k22:Number; var k12:Number; var k_maxConditionNumber:Number; m_step = new b2TimeStep(); m_constraints = new Array(); super(); m_step.dt = step.dt; m_step.inv_dt = step.inv_dt; m_step.positionIterations = step.positionIterations; m_step.velocityIterations = step.velocityIterations; m_allocator = allocator; m_constraintCount = 0; i = 0; while (i < contactCount) { contact = contacts[i]; m_constraintCount = (m_constraintCount + contact.m_manifoldCount); i++; }; i = 0; while (i < m_constraintCount) { m_constraints[i] = new b2ContactConstraint(); i++; }; var count:int; i = 0; while (i < contactCount) { contact = contacts[i]; shape1 = contact.m_shape1; shape2 = contact.m_shape2; b1 = shape1.m_body; b2 = shape2.m_body; manifoldCount = contact.m_manifoldCount; manifolds = contact.GetManifolds(); friction = b2Settings.b2MixFriction(shape1.GetFriction(), shape2.GetFriction()); restitution = b2Settings.b2MixRestitution(shape1.GetRestitution(), shape2.GetRestitution()); v1X = b1.m_linearVelocity.x; v1Y = b1.m_linearVelocity.y; v2X = b2.m_linearVelocity.x; v2Y = b2.m_linearVelocity.y; w1 = b1.m_angularVelocity; w2 = b2.m_angularVelocity; j = 0; while (j < manifoldCount) { manifold = manifolds[j]; normalX = manifold.normal.x; normalY = manifold.normal.y; cc = m_constraints[count]; cc.body1 = b1; cc.body2 = b2; cc.manifold = manifold; cc.normal.x = normalX; cc.normal.y = normalY; cc.pointCount = manifold.pointCount; cc.friction = friction; cc.restitution = restitution; k = 0; while (k < cc.pointCount) { cp = manifold.points[k]; ccp = cc.points[k]; ccp.normalImpulse = cp.normalImpulse; ccp.tangentImpulse = cp.tangentImpulse; ccp.separation = cp.separation; ccp.localAnchor1.SetV(cp.localPoint1); ccp.localAnchor2.SetV(cp.localPoint2); tMat = b1.m_xf.R; r1X = (cp.localPoint1.x - b1.m_sweep.localCenter.x); r1Y = (cp.localPoint1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; ccp.r1.Set(r1X, r1Y); tMat = b2.m_xf.R; r2X = (cp.localPoint2.x - b2.m_sweep.localCenter.x); r2Y = (cp.localPoint2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; ccp.r2.Set(r2X, r2Y); rn1 = ((r1X * normalY) - (r1Y * normalX)); rn2 = ((r2X * normalY) - (r2Y * normalX)); rn1 = (rn1 * rn1); rn2 = (rn2 * rn2); kNormal = (((b1.m_invMass + b2.m_invMass) + (b1.m_invI * rn1)) + (b2.m_invI * rn2)); ccp.normalMass = (1 / kNormal); kEqualized = ((b1.m_mass * b1.m_invMass) + (b2.m_mass * b2.m_invMass)); kEqualized = (kEqualized + (((b1.m_mass * b1.m_invI) * rn1) + ((b2.m_mass * b2.m_invI) * rn2))); ccp.equalizedMass = (1 / kEqualized); tangentX = normalY; tangentY = -(normalX); rt1 = ((r1X * tangentY) - (r1Y * tangentX)); rt2 = ((r2X * tangentY) - (r2Y * tangentX)); rt1 = (rt1 * rt1); rt2 = (rt2 * rt2); kTangent = (((b1.m_invMass + b2.m_invMass) + (b1.m_invI * rt1)) + (b2.m_invI * rt2)); ccp.tangentMass = (1 / kTangent); ccp.velocityBias = 0; if (ccp.separation > 0){ ccp.velocityBias = (-60 * ccp.separation); } else { tX = (((v2X + (-(w2) * r2Y)) - v1X) - (-(w1) * r1Y)); tY = (((v2Y + (w2 * r2X)) - v1Y) - (w1 * r1X)); vRel = ((cc.normal.x * tX) + (cc.normal.y * tY)); if (vRel < -(b2Settings.b2_velocityThreshold)){ ccp.velocityBias = (ccp.velocityBias + (-(cc.restitution) * vRel)); }; }; k++; }; if (cc.pointCount == 2){ ccp1 = cc.points[0]; ccp2 = cc.points[1]; invMass1 = b1.m_invMass; invI1 = b1.m_invI; invMass2 = b2.m_invMass; invI2 = b2.m_invI; rn11 = ((ccp1.r1.x * normalY) - (ccp1.r1.y * normalX)); rn12 = ((ccp1.r2.x * normalY) - (ccp1.r2.y * normalX)); rn21 = ((ccp2.r1.x * normalY) - (ccp2.r1.y * normalX)); rn22 = ((ccp2.r2.x * normalY) - (ccp2.r2.y * normalX)); k11 = (((invMass1 + invMass2) + ((invI1 * rn11) * rn11)) + ((invI2 * rn12) * rn12)); k22 = (((invMass1 + invMass2) + ((invI1 * rn21) * rn21)) + ((invI2 * rn22) * rn22)); k12 = (((invMass1 + invMass2) + ((invI1 * rn11) * rn21)) + ((invI2 * rn12) * rn22)); k_maxConditionNumber = 100; if ((k11 * k11) < (k_maxConditionNumber * ((k11 * k22) - (k12 * k12)))){ cc.K.col1.Set(k11, k12); cc.K.col2.Set(k12, k22); cc.K.GetInverse(cc.normalMass); } else { cc.pointCount = 1; }; }; count++; j++; }; i++; }; } public function InitVelocityConstraints(step:b2TimeStep):void{ var tVec:b2Vec2; var tVec2:b2Vec2; var tMat:b2Mat22; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tangentX:Number; var tangentY:Number; var tX:Number; var j:int; var tCount:int; var ccp:b2ContactConstraintPoint; var PX:Number; var PY:Number; var ccp2:b2ContactConstraintPoint; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; invMass1 = b1.m_invMass; invI1 = b1.m_invI; invMass2 = b2.m_invMass; invI2 = b2.m_invI; normalX = c.normal.x; normalY = c.normal.y; tangentX = normalY; tangentY = -(normalX); if (step.warmStarting){ tCount = c.pointCount; j = 0; while (j < tCount) { ccp = c.points[j]; ccp.normalImpulse = (ccp.normalImpulse * step.dtRatio); ccp.tangentImpulse = (ccp.tangentImpulse * step.dtRatio); PX = ((ccp.normalImpulse * normalX) + (ccp.tangentImpulse * tangentX)); PY = ((ccp.normalImpulse * normalY) + (ccp.tangentImpulse * tangentY)); b1.m_angularVelocity = (b1.m_angularVelocity - (invI1 * ((ccp.r1.x * PY) - (ccp.r1.y * PX)))); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (invMass1 * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (invMass1 * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (invI2 * ((ccp.r2.x * PY) - (ccp.r2.y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (invMass2 * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (invMass2 * PY)); j++; }; } else { tCount = c.pointCount; j = 0; while (j < tCount) { ccp2 = c.points[j]; ccp2.normalImpulse = 0; ccp2.tangentImpulse = 0; j++; }; }; i++; }; } public function SolvePositionConstraints(baumgarte:Number):Boolean{ var tMat:b2Mat22; var tVec:b2Vec2; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var b1_sweep_c:b2Vec2; var b1_sweep_a:Number; var b2_sweep_c:b2Vec2; var b2_sweep_a:Number; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tCount:int; var j:int; var ccp:b2ContactConstraintPoint; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var tX:Number; var p1X:Number; var p1Y:Number; var p2X:Number; var p2Y:Number; var dpX:Number; var dpY:Number; var separation:Number; var C:Number; var dImpulse:Number; var PX:Number; var PY:Number; var minSeparation:Number = 0; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; b1_sweep_c = b1.m_sweep.c; b1_sweep_a = b1.m_sweep.a; b2_sweep_c = b2.m_sweep.c; b2_sweep_a = b2.m_sweep.a; invMass1 = (b1.m_mass * b1.m_invMass); invI1 = (b1.m_mass * b1.m_invI); invMass2 = (b2.m_mass * b2.m_invMass); invI2 = (b2.m_mass * b2.m_invI); normalX = c.normal.x; normalY = c.normal.y; tCount = c.pointCount; j = 0; while (j < tCount) { ccp = c.points[j]; tMat = b1.m_xf.R; tVec = b1.m_sweep.localCenter; r1X = (ccp.localAnchor1.x - tVec.x); r1Y = (ccp.localAnchor1.y - tVec.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; tVec = b2.m_sweep.localCenter; r2X = (ccp.localAnchor2.x - tVec.x); r2Y = (ccp.localAnchor2.y - tVec.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p1X = (b1_sweep_c.x + r1X); p1Y = (b1_sweep_c.y + r1Y); p2X = (b2_sweep_c.x + r2X); p2Y = (b2_sweep_c.y + r2Y); dpX = (p2X - p1X); dpY = (p2Y - p1Y); separation = (((dpX * normalX) + (dpY * normalY)) + ccp.separation); minSeparation = b2Math.b2Min(minSeparation, separation); C = (baumgarte * b2Math.b2Clamp((separation + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0)); dImpulse = (-(ccp.equalizedMass) * C); PX = (dImpulse * normalX); PY = (dImpulse * normalY); b1_sweep_c.x = (b1_sweep_c.x - (invMass1 * PX)); b1_sweep_c.y = (b1_sweep_c.y - (invMass1 * PY)); b1_sweep_a = (b1_sweep_a - (invI1 * ((r1X * PY) - (r1Y * PX)))); b1.m_sweep.a = b1_sweep_a; b1.SynchronizeTransform(); b2_sweep_c.x = (b2_sweep_c.x + (invMass2 * PX)); b2_sweep_c.y = (b2_sweep_c.y + (invMass2 * PY)); b2_sweep_a = (b2_sweep_a + (invI2 * ((r2X * PY) - (r2Y * PX)))); b2.m_sweep.a = b2_sweep_a; b2.SynchronizeTransform(); j++; }; i++; }; return ((minSeparation >= (-1.5 * b2Settings.b2_linearSlop))); } public function SolveVelocityConstraints():void{ var j:int; var ccp:b2ContactConstraintPoint; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var dvX:Number; var dvY:Number; var vn:Number; var vt:Number; var lambda_n:Number; var lambda_t:Number; var newImpulse_n:Number; var newImpulse_t:Number; var PX:Number; var PY:Number; var dX:Number; var dY:Number; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; var tMat:b2Mat22; var tVec:b2Vec2; var c:b2ContactConstraint; var b1:b2Body; var b2:b2Body; var w1:Number; var w2:Number; var v1:b2Vec2; var v2:b2Vec2; var invMass1:Number; var invI1:Number; var invMass2:Number; var invI2:Number; var normalX:Number; var normalY:Number; var tangentX:Number; var tangentY:Number; var friction:Number; var tX:Number; var tCount:int; var maxFriction:Number; var cp1:b2ContactConstraintPoint; var cp2:b2ContactConstraintPoint; var aX:Number; var aY:Number; var dv1X:Number; var dv1Y:Number; var dv2X:Number; var dv2Y:Number; var vn1:Number; var vn2:Number; var bX:Number; var bY:Number; var k_errorTol:Number; var xX:Number; var xY:Number; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; b1 = c.body1; b2 = c.body2; w1 = b1.m_angularVelocity; w2 = b2.m_angularVelocity; v1 = b1.m_linearVelocity; v2 = b2.m_linearVelocity; invMass1 = b1.m_invMass; invI1 = b1.m_invI; invMass2 = b2.m_invMass; invI2 = b2.m_invI; normalX = c.normal.x; normalY = c.normal.y; tangentX = normalY; tangentY = -(normalX); friction = c.friction; tCount = c.pointCount; if (c.pointCount == 1){ ccp = c.points[0]; dvX = (((v2.x + (-(w2) * ccp.r2.y)) - v1.x) - (-(w1) * ccp.r1.y)); dvY = (((v2.y + (w2 * ccp.r2.x)) - v1.y) - (w1 * ccp.r1.x)); vn = ((dvX * normalX) + (dvY * normalY)); lambda_n = (-(ccp.normalMass) * (vn - ccp.velocityBias)); vt = ((dvX * tangentX) + (dvY * tangentY)); lambda_t = (ccp.tangentMass * -(vt)); newImpulse_n = b2Math.b2Max((ccp.normalImpulse + lambda_n), 0); lambda_n = (newImpulse_n - ccp.normalImpulse); maxFriction = (friction * ccp.normalImpulse); newImpulse_t = b2Math.b2Clamp((ccp.tangentImpulse + lambda_t), -(maxFriction), maxFriction); lambda_t = (newImpulse_t - ccp.tangentImpulse); PX = ((lambda_n * normalX) + (lambda_t * tangentX)); PY = ((lambda_n * normalY) + (lambda_t * tangentY)); v1.x = (v1.x - (invMass1 * PX)); v1.y = (v1.y - (invMass1 * PY)); w1 = (w1 - (invI1 * ((ccp.r1.x * PY) - (ccp.r1.y * PX)))); v2.x = (v2.x + (invMass2 * PX)); v2.y = (v2.y + (invMass2 * PY)); w2 = (w2 + (invI2 * ((ccp.r2.x * PY) - (ccp.r2.y * PX)))); ccp.normalImpulse = newImpulse_n; ccp.tangentImpulse = newImpulse_t; } else { cp1 = c.points[0]; cp2 = c.points[1]; aX = cp1.normalImpulse; aY = cp2.normalImpulse; dv1X = (((v2.x - (w2 * cp1.r2.y)) - v1.x) + (w1 * cp1.r1.y)); dv1Y = (((v2.y + (w2 * cp1.r2.x)) - v1.y) - (w1 * cp1.r1.x)); dv2X = (((v2.x - (w2 * cp2.r2.y)) - v1.x) + (w1 * cp2.r1.y)); dv2Y = (((v2.y + (w2 * cp2.r2.x)) - v1.y) - (w1 * cp2.r1.x)); vn1 = ((dv1X * normalX) + (dv1Y * normalY)); vn2 = ((dv2X * normalX) + (dv2Y * normalY)); bX = (vn1 - cp1.velocityBias); bY = (vn2 - cp2.velocityBias); tMat = c.K; bX = (bX - ((tMat.col1.x * aX) + (tMat.col2.x * aY))); bY = (bY - ((tMat.col1.y * aX) + (tMat.col2.y * aY))); k_errorTol = 0.001; while (true) { tMat = c.normalMass; xX = -(((tMat.col1.x * bX) + (tMat.col2.x * bY))); xY = -(((tMat.col1.y * bX) + (tMat.col2.y * bY))); if ((((xX >= 0)) && ((xY >= 0)))){ dX = (xX - aX); dY = (xY - aY); P1X = (dX * normalX); P1Y = (dX * normalY); P2X = (dY * normalX); P2Y = (dY * normalY); v1.x = (v1.x - (invMass1 * (P1X + P2X))); v1.y = (v1.y - (invMass1 * (P1Y + P2Y))); w1 = (w1 - (invI1 * ((((cp1.r1.x * P1Y) - (cp1.r1.y * P1X)) + (cp2.r1.x * P2Y)) - (cp2.r1.y * P2X)))); v2.x = (v2.x + (invMass2 * (P1X + P2X))); v2.y = (v2.y + (invMass2 * (P1Y + P2Y))); w2 = (w2 + (invI2 * ((((cp1.r2.x * P1Y) - (cp1.r2.y * P1X)) + (cp2.r2.x * P2Y)) - (cp2.r2.y * P2X)))); cp1.normalImpulse = xX; cp2.normalImpulse = xY; break; }; xX = (-(cp1.normalMass) * bX); xY = 0; vn1 = 0; vn2 = ((c.K.col1.y * xX) + bY); if ((((xX >= 0)) && ((vn2 >= 0)))){ dX = (xX - aX); dY = (xY - aY); P1X = (dX * normalX); P1Y = (dX * normalY); P2X = (dY * normalX); P2Y = (dY * normalY); v1.x = (v1.x - (invMass1 * (P1X + P2X))); v1.y = (v1.y - (invMass1 * (P1Y + P2Y))); w1 = (w1 - (invI1 * ((((cp1.r1.x * P1Y) - (cp1.r1.y * P1X)) + (cp2.r1.x * P2Y)) - (cp2.r1.y * P2X)))); v2.x = (v2.x + (invMass2 * (P1X + P2X))); v2.y = (v2.y + (invMass2 * (P1Y + P2Y))); w2 = (w2 + (invI2 * ((((cp1.r2.x * P1Y) - (cp1.r2.y * P1X)) + (cp2.r2.x * P2Y)) - (cp2.r2.y * P2X)))); cp1.normalImpulse = xX; cp2.normalImpulse = xY; break; }; xX = 0; xY = (-(cp2.normalMass) * bY); vn1 = ((c.K.col2.x * xY) + bX); vn2 = 0; if ((((xY >= 0)) && ((vn1 >= 0)))){ dX = (xX - aX); dY = (xY - aY); P1X = (dX * normalX); P1Y = (dX * normalY); P2X = (dY * normalX); P2Y = (dY * normalY); v1.x = (v1.x - (invMass1 * (P1X + P2X))); v1.y = (v1.y - (invMass1 * (P1Y + P2Y))); w1 = (w1 - (invI1 * ((((cp1.r1.x * P1Y) - (cp1.r1.y * P1X)) + (cp2.r1.x * P2Y)) - (cp2.r1.y * P2X)))); v2.x = (v2.x + (invMass2 * (P1X + P2X))); v2.y = (v2.y + (invMass2 * (P1Y + P2Y))); w2 = (w2 + (invI2 * ((((cp1.r2.x * P1Y) - (cp1.r2.y * P1X)) + (cp2.r2.x * P2Y)) - (cp2.r2.y * P2X)))); cp1.normalImpulse = xX; cp2.normalImpulse = xY; break; }; xX = 0; xY = 0; vn1 = bX; vn2 = bY; if ((((vn1 >= 0)) && ((vn2 >= 0)))){ dX = (xX - aX); dY = (xY - aY); P1X = (dX * normalX); P1Y = (dX * normalY); P2X = (dY * normalX); P2Y = (dY * normalY); v1.x = (v1.x - (invMass1 * (P1X + P2X))); v1.y = (v1.y - (invMass1 * (P1Y + P2Y))); w1 = (w1 - (invI1 * ((((cp1.r1.x * P1Y) - (cp1.r1.y * P1X)) + (cp2.r1.x * P2Y)) - (cp2.r1.y * P2X)))); v2.x = (v2.x + (invMass2 * (P1X + P2X))); v2.y = (v2.y + (invMass2 * (P1Y + P2Y))); w2 = (w2 + (invI2 * ((((cp1.r2.x * P1Y) - (cp1.r2.y * P1X)) + (cp2.r2.x * P2Y)) - (cp2.r2.y * P2X)))); cp1.normalImpulse = xX; cp2.normalImpulse = xY; break; }; break; }; j = 0; while (j < c.pointCount) { ccp = c.points[j]; dvX = (((v2.x - (w2 * ccp.r2.y)) - v1.x) + (w1 * ccp.r1.y)); dvY = (((v2.y + (w2 * ccp.r2.x)) - v1.y) - (w1 * ccp.r1.x)); vt = ((dvX * tangentX) + (dvY * tangentY)); lambda_t = (ccp.tangentMass * -(vt)); maxFriction = (friction * ccp.normalImpulse); newImpulse_t = b2Math.b2Clamp((ccp.tangentImpulse + lambda_t), -(maxFriction), maxFriction); lambda_t = (newImpulse_t - ccp.tangentImpulse); PX = (lambda_t * tangentX); PY = (lambda_t * tangentY); v1.x = (v1.x - (invMass1 * PX)); v1.y = (v1.y - (invMass1 * PY)); w1 = (w1 - (invI1 * ((ccp.r1.x * PY) - (ccp.r1.y * PX)))); v2.x = (v2.x + (invMass2 * PX)); v2.y = (v2.y + (invMass2 * PY)); w2 = (w2 + (invI2 * ((ccp.r2.x * PY) - (ccp.r2.y * PX)))); ccp.tangentImpulse = newImpulse_t; j++; }; }; b1.m_angularVelocity = w1; b2.m_angularVelocity = w2; i++; }; } public function FinalizeVelocityConstraints():void{ var c:b2ContactConstraint; var m:b2Manifold; var j:int; var point1:b2ManifoldPoint; var point2:b2ContactConstraintPoint; var i:int; while (i < m_constraintCount) { c = m_constraints[i]; m = c.manifold; j = 0; while (j < c.pointCount) { point1 = m.points[j]; point2 = c.points[j]; point1.normalImpulse = point2.normalImpulse; point1.tangentImpulse = point2.tangentImpulse; j++; }; i++; }; } } }//package Box2D.Dynamics.Contacts
Section 49
//b2EdgeAndCircleContact (Box2D.Dynamics.Contacts.b2EdgeAndCircleContact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2EdgeAndCircleContact extends b2Contact { private var m_manifolds:Array; private var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2EdgeAndCircleContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; m_manifold.pointCount = 0; var point:b2ManifoldPoint = m_manifold.points[0]; point.normalImpulse = 0; point.tangentImpulse = 0; } override b2internal function Evaluate(listener:b2ContactListener):void{ var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2CollideEdgeAndCircle(m_manifold, (m_shape1 as b2EdgeShape), b1.m_xf, (m_shape2 as b2CircleShape), b2.m_xf); var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = b2Settings.b2MixFriction(m_shape1.GetFriction(), m_shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(m_shape1.GetRestitution(), m_shape2.GetRestitution()); if (m_manifold.pointCount > 0){ m_manifoldCount = 1; mp = m_manifold.points[0]; if (m0.pointCount == 0){ mp.normalImpulse = 0; mp.tangentImpulse = 0; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Add(cp); }; } else { mp0 = m0.points[0]; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; if (listener){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = mp.id._key; listener.Persist(cp); }; }; } else { m_manifoldCount = 0; if ((((m0.pointCount > 0)) && (listener))){ mp0 = m0.points[0]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; }; } private function b2CollideEdgeAndCircle(manifold:b2Manifold, edge:b2EdgeShape, xf1:b2XForm, circle:b2CircleShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec:b2Vec2; var dX:Number; var dY:Number; var tX:Number; var tY:Number; var tPoint:b2ManifoldPoint; var separation:Number; var distSqr:Number; manifold.pointCount = 0; tMat = xf2.R; tVec = circle.m_localPosition; var cX:Number = (xf2.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); var cY:Number = (xf2.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); tMat = xf1.R; tX = (cX - xf1.position.x); tY = (cY - xf1.position.y); var cLocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var cLocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var n:b2Vec2 = edge.m_normal; var v1:b2Vec2 = edge.m_v1; var v2:b2Vec2 = edge.m_v2; var radius:Number = circle.m_radius; var dirDist:Number = (((cLocalX - v1.x) * edge.m_direction.x) + ((cLocalY - v1.y) * edge.m_direction.y)); var normalCalculated:Boolean; if (dirDist <= 0){ dX = (cLocalX - v1.x); dY = (cLocalY - v1.y); if (((dX * edge.m_cornerDir1.x) + (dY * edge.m_cornerDir1.y)) < 0){ return; }; dX = (cX - (xf1.position.x + ((tMat.col1.x * v1.x) + (tMat.col2.x * v1.y)))); dY = (cY - (xf1.position.y + ((tMat.col1.y * v1.x) + (tMat.col2.y * v1.y)))); } else { if (dirDist >= edge.m_length){ dX = (cLocalX - v2.x); dY = (cLocalY - v2.y); if (((dX * edge.m_cornerDir2.x) + (dY * edge.m_cornerDir2.y)) > 0){ return; }; dX = (cX - (xf1.position.x + ((tMat.col1.x * v2.x) + (tMat.col2.x * v2.y)))); dY = (cY - (xf1.position.y + ((tMat.col1.y * v2.x) + (tMat.col2.y * v2.y)))); } else { separation = (((cLocalX - v1.x) * n.x) + ((cLocalY - v1.y) * n.y)); if ((((separation > radius)) || ((separation < -(radius))))){ return; }; separation = (separation - radius); tMat = xf1.R; manifold.normal.x = ((tMat.col1.x * n.x) + (tMat.col2.x * n.y)); manifold.normal.y = ((tMat.col1.y * n.x) + (tMat.col2.y * n.y)); normalCalculated = true; }; }; if (!normalCalculated){ distSqr = ((dX * dX) + (dY * dY)); if (distSqr > (radius * radius)){ return; }; if (distSqr < Number.MIN_VALUE){ separation = -(radius); manifold.normal.x = ((tMat.col1.x * n.x) + (tMat.col2.x * n.y)); manifold.normal.y = ((tMat.col1.y * n.x) + (tMat.col2.y * n.y)); } else { distSqr = Math.sqrt(distSqr); dX = (dX / distSqr); dY = (dY / distSqr); separation = (distSqr - radius); manifold.normal.x = dX; manifold.normal.y = dY; }; }; tPoint = manifold.points[0]; manifold.pointCount = 1; tPoint.id.key = 0; tPoint.separation = separation; cX = (cX - (radius * manifold.normal.x)); cY = (cY - (radius * manifold.normal.y)); tX = (cX - xf1.position.x); tY = (cY - xf1.position.y); tPoint.localPoint1.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); tPoint.localPoint1.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tMat = xf2.R; tX = (cX - xf2.position.x); tY = (cY - xf2.position.y); tPoint.localPoint2.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); tPoint.localPoint2.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2EdgeAndCircleContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 50
//b2NullContact (Box2D.Dynamics.Contacts.b2NullContact) package Box2D.Dynamics.Contacts { import Box2D.Dynamics.*; import Box2D.Common.*; public class b2NullContact extends b2Contact { public function b2NullContact(){ super(); } override b2internal function Evaluate(l:b2ContactListener):void{ } override public function GetManifolds():Array{ return (null); } } }//package Box2D.Dynamics.Contacts
Section 51
//b2PolyAndCircleContact (Box2D.Dynamics.Contacts.b2PolyAndCircleContact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2PolyAndCircleContact extends b2Contact { private var m_manifolds:Array; private var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2PolyAndCircleContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; b2Settings.b2Assert((m_shape1.m_type == b2Shape.e_polygonShape)); b2Settings.b2Assert((m_shape2.m_type == b2Shape.e_circleShape)); m_manifold.pointCount = 0; } override b2internal function Evaluate(listener:b2ContactListener):void{ var i:int; var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var found:Boolean; var idKey:uint; var j:int; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollidePolygonAndCircle(m_manifold, (m_shape1 as b2PolygonShape), b1.m_xf, (m_shape2 as b2CircleShape), b2.m_xf); var persisted:Array = [false, false]; var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = b2Settings.b2MixFriction(m_shape1.GetFriction(), m_shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(m_shape1.GetRestitution(), m_shape2.GetRestitution()); if (m_manifold.pointCount > 0){ i = 0; while (i < m_manifold.pointCount) { mp = m_manifold.points[i]; mp.normalImpulse = 0; mp.tangentImpulse = 0; found = false; idKey = mp.id._key; j = 0; while (j < m0.pointCount) { if (persisted[j] == true){ } else { mp0 = m0.points[j]; if (mp0.id._key == idKey){ persisted[j] = true; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; found = true; if (listener != null){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Persist(cp); }; break; }; }; j++; }; if ((((found == false)) && (!((listener == null))))){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Add(cp); }; i++; }; m_manifoldCount = 1; } else { m_manifoldCount = 0; }; if (listener == null){ return; }; i = 0; while (i < m0.pointCount) { if (persisted[i]){ } else { mp0 = m0.points[i]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; i++; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2PolyAndCircleContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 52
//b2PolyAndEdgeContact (Box2D.Dynamics.Contacts.b2PolyAndEdgeContact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2PolyAndEdgeContact extends b2Contact { private var m_manifolds:Array; private var m_manifold:b2Manifold; private var m0:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2PolyAndEdgeContact(shape1:b2Shape, shape2:b2Shape){ m_manifolds = [new b2Manifold()]; m0 = new b2Manifold(); super(shape1, shape2); m_manifold = m_manifolds[0]; b2Settings.b2Assert((m_shape1.m_type == b2Shape.e_polygonShape)); b2Settings.b2Assert((m_shape2.m_type == b2Shape.e_edgeShape)); m_manifold.pointCount = 0; } override b2internal function Evaluate(listener:b2ContactListener):void{ var i:int; var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var mp:b2ManifoldPoint; var found:Boolean; var idKey:uint; var j:int; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2CollidePolyAndEdge(m_manifold, (m_shape1 as b2PolygonShape), b1.m_xf, (m_shape2 as b2EdgeShape), b2.m_xf); var persisted:Array = [false, false]; var cp:b2ContactPoint = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = b2Settings.b2MixFriction(m_shape1.GetFriction(), m_shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(m_shape1.GetRestitution(), m_shape2.GetRestitution()); if (m_manifold.pointCount > 0){ i = 0; while (i < m_manifold.pointCount) { mp = m_manifold.points[i]; mp.normalImpulse = 0; mp.tangentImpulse = 0; found = false; idKey = mp.id._key; j = 0; while (j < m0.pointCount) { if (persisted[j] == true){ } else { mp0 = m0.points[j]; if (mp0.id._key == idKey){ persisted[j] = true; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; found = true; if (listener != null){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Persist(cp); }; break; }; }; j++; }; if ((((found == false)) && (!((listener == null))))){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Add(cp); }; i++; }; m_manifoldCount = 1; } else { m_manifoldCount = 0; }; if (listener == null){ return; }; i = 0; while (i < m0.pointCount) { if (persisted[i]){ } else { mp0 = m0.points[i]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; i++; }; } private function b2CollidePolyAndEdge(manifold:b2Manifold, polygon:b2PolygonShape, xf1:b2XForm, edge:b2EdgeShape, xf2:b2XForm):void{ var tMat:b2Mat22; var tVec1:b2Vec2; var tVec2:b2Vec2; var tX:Number; var tY:Number; var tPoint:b2ManifoldPoint; var ratio:Number; var separation1:Number; var separation2:Number; var dirProj2:Number; manifold.pointCount = 0; tMat = xf2.R; tVec1 = edge.m_v1; var v1X:Number = (xf2.position.x + ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y))); var v1Y:Number = (xf2.position.y + ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y))); tVec1 = edge.m_v2; var v2X:Number = (xf2.position.x + ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y))); var v2Y:Number = (xf2.position.y + ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y))); tVec1 = edge.m_normal; var nX:Number = ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y)); var nY:Number = ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y)); tMat = xf1.R; tX = (v1X - xf1.position.x); tY = (v1Y - xf1.position.y); var v1LocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var v1LocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tX = (v2X - xf1.position.x); tY = (v2Y - xf1.position.y); var v2LocalX:Number = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); var v2LocalY:Number = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); var nLocalX:Number = ((nX * tMat.col1.x) + (nY * tMat.col1.y)); var nLocalY:Number = ((nX * tMat.col2.x) + (nY * tMat.col2.y)); var separationIndex1 = -1; var separationMax1:Number = -(Number.MAX_VALUE); var separationIndex2 = -1; var separationMax2:Number = -(Number.MAX_VALUE); var separationMax:Number = -(Number.MAX_VALUE); var separationV1:Boolean; var separationIndex = -1; var vertexCount:int = polygon.m_vertexCount; var vertices:Array = polygon.m_vertices; var normals:Array = polygon.m_normals; var enterStartIndex = -1; var enterEndIndex = -1; var exitStartIndex = -1; var exitEndIndex = -1; var prevSepN:Number = 0; var nextSepN:Number = 0; var enterSepN:Number = 0; var exitSepN:Number = 0; var deepestSepN:Number = Number.MAX_VALUE; tVec1 = vertices[(vertexCount - 1)]; prevSepN = (((tVec1.x - v1LocalX) * nLocalX) + ((tVec1.y - v1LocalY) * nLocalY)); var i:int; while (i < vertexCount) { tVec1 = vertices[i]; tVec2 = normals[i]; separation1 = (((v1LocalX - tVec1.x) * tVec2.x) + ((v1LocalY - tVec1.y) * tVec2.y)); separation2 = (((v2LocalX - tVec1.x) * tVec2.x) + ((v2LocalY - tVec1.y) * tVec2.y)); if (separation2 < separation1){ if (separation2 > separationMax){ separationMax = separation2; separationV1 = false; separationIndex = i; }; } else { if (separation1 > separationMax){ separationMax = separation1; separationV1 = true; separationIndex = i; }; }; if (separation1 > separationMax1){ separationMax1 = separation1; separationIndex1 = i; }; if (separation2 > separationMax2){ separationMax2 = separation2; separationIndex2 = i; }; nextSepN = (((tVec1.x - v1LocalX) * nLocalX) + ((tVec1.y - v1LocalY) * nLocalY)); if ((((nextSepN >= 0)) && ((prevSepN < 0)))){ exitStartIndex = ((i)==0) ? (vertexCount - 1) : (i - 1); exitEndIndex = i; exitSepN = prevSepN; } else { if ((((nextSepN < 0)) && ((prevSepN >= 0)))){ enterStartIndex = ((i)==0) ? (vertexCount - 1) : (i - 1); enterEndIndex = i; enterSepN = nextSepN; }; }; if (nextSepN < deepestSepN){ deepestSepN = nextSepN; }; prevSepN = nextSepN; i++; }; if (enterStartIndex == -1){ return; }; if (separationMax > 0){ return; }; if (((((separationV1) && (edge.m_cornerConvex1))) || (((!(separationV1)) && (edge.m_cornerConvex2))))){ if (separationMax > (deepestSepN + b2Settings.b2_linearSlop)){ if (separationV1){ tMat = xf2.R; tVec1 = edge.m_cornerDir1; tX = ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y)); tY = ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y)); tMat = xf1.R; v1X = ((tMat.col1.x * tX) + (tMat.col2.x * tY)); v1Y = ((tMat.col1.y * tX) + (tMat.col2.y * tY)); tVec2 = normals[separationIndex1]; if (((tVec2.x * v1X) + (tVec2.y * v1Y)) >= 0){ return; }; } else { tMat = xf2.R; tVec1 = edge.m_cornerDir2; tX = ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y)); tY = ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y)); tMat = xf1.R; v1X = ((tMat.col1.x * tX) + (tMat.col2.x * tY)); v1Y = ((tMat.col1.y * tX) + (tMat.col2.y * tY)); tVec2 = normals[separationIndex2]; if (((tVec2.x * v1X) + (tVec2.y * v1Y)) <= 0){ return; }; }; tPoint = manifold.points[0]; manifold.pointCount = 1; tMat = xf1.R; tVec2 = normals[separationIndex]; manifold.normal.x = ((tMat.col1.x * tVec2.x) + (tMat.col2.x * tVec2.y)); manifold.normal.y = ((tMat.col1.y * tVec2.x) + (tMat.col2.y * tVec2.y)); tPoint.separation = separationMax; tPoint.id.features.incidentEdge = separationIndex; tPoint.id.features.incidentVertex = b2Collision.b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; if (separationV1){ tPoint.localPoint1.x = v1LocalX; tPoint.localPoint1.y = v1LocalY; tPoint.localPoint2.x = edge.m_v1.x; tPoint.localPoint2.y = edge.m_v1.y; } else { tPoint.localPoint1.x = v2LocalX; tPoint.localPoint1.y = v2LocalY; tPoint.localPoint2.x = edge.m_v2.x; tPoint.localPoint2.y = edge.m_v2.y; }; return; }; }; manifold.normal.x = -(nX); manifold.normal.y = -(nY); if (enterEndIndex == exitStartIndex){ tPoint = manifold.points[0]; manifold.pointCount = 1; tPoint.id.features.incidentEdge = enterEndIndex; tPoint.id.features.incidentVertex = b2Collision.b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; tVec1 = vertices[enterEndIndex]; tPoint.localPoint1.x = tVec1.x; tPoint.localPoint1.y = tVec1.y; tMat = xf1.R; tX = ((xf1.position.x + ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y))) - xf2.position.x); tY = ((xf1.position.y + ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y))) - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); tPoint.localPoint2.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tPoint.separation = enterSepN; return; }; manifold.pointCount = 2; tX = -(nLocalY); tY = nLocalX; tVec1 = vertices[enterEndIndex]; var dirProj1:Number = ((tX * (tVec1.x - v1LocalX)) + (tY * (tVec1.y - v1LocalY))); exitEndIndex = ((enterEndIndex)==(vertexCount - 1)) ? 0 : (enterEndIndex + 1); tVec1 = vertices[exitStartIndex]; if (exitEndIndex != exitStartIndex){ exitStartIndex = exitEndIndex; exitSepN = ((nLocalX * (tVec1.x - v1LocalX)) + (nLocalY * (tVec1.y - v1LocalY))); }; dirProj2 = ((tX * (tVec1.x - v1LocalX)) + (tY * (tVec1.y - v1LocalY))); tPoint = manifold.points[0]; tPoint.id.features.incidentEdge = enterEndIndex; tPoint.id.features.incidentVertex = b2Collision.b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; if (dirProj1 > edge.m_length){ tPoint.localPoint1.x = v2LocalX; tPoint.localPoint1.y = v2LocalY; tPoint.localPoint2.x = edge.m_v2.x; tPoint.localPoint2.y = edge.m_v2.y; ratio = ((edge.m_length - dirProj2) / (dirProj1 - dirProj2)); if ((((ratio > (100 * Number.MIN_VALUE))) && ((ratio < 1)))){ tPoint.separation = ((exitSepN * (1 - ratio)) + (enterSepN * ratio)); } else { tPoint.separation = enterSepN; }; } else { tVec1 = vertices[enterEndIndex]; tPoint.localPoint1.x = tVec1.x; tPoint.localPoint1.y = tVec1.y; tMat = xf1.R; tX = ((xf1.position.x + ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y))) - xf2.position.x); tY = ((xf1.position.y + ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y))) - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); tPoint.localPoint2.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tPoint.separation = enterSepN; }; tPoint = manifold.points[1]; tPoint.id.features.incidentEdge = exitStartIndex; tPoint.id.features.incidentVertex = b2Collision.b2_nullFeature; tPoint.id.features.referenceEdge = 0; tPoint.id.features.flip = 0; if (dirProj2 < 0){ tPoint.localPoint1.x = v1LocalX; tPoint.localPoint1.y = v1LocalY; tPoint.localPoint2.x = edge.m_v1.x; tPoint.localPoint2.y = edge.m_v1.y; ratio = (-(dirProj1) / (dirProj2 - dirProj1)); if ((((ratio > (100 * Number.MIN_VALUE))) && ((ratio < 1)))){ tPoint.separation = ((enterSepN * (1 - ratio)) + (exitSepN * ratio)); } else { tPoint.separation = exitSepN; }; } else { tVec1 = vertices[exitStartIndex]; tPoint.localPoint1.x = tVec1.x; tPoint.localPoint1.y = tVec1.y; tMat = xf1.R; tX = ((xf1.position.x + ((tMat.col1.x * tVec1.x) + (tMat.col2.x * tVec1.y))) - xf2.position.x); tY = ((xf1.position.y + ((tMat.col1.y * tVec1.x) + (tMat.col2.y * tVec1.y))) - xf2.position.y); tMat = xf2.R; tPoint.localPoint2.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); tPoint.localPoint2.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); tPoint.separation = exitSepN; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2PolyAndEdgeContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 53
//b2PolygonContact (Box2D.Dynamics.Contacts.b2PolygonContact) package Box2D.Dynamics.Contacts { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Common.*; public class b2PolygonContact extends b2Contact { private var m_manifolds:Array; private var m0:b2Manifold; private var m_manifold:b2Manifold; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2PolygonContact(shape1:b2Shape, shape2:b2Shape):void{ m0 = new b2Manifold(); m_manifolds = [new b2Manifold()]; super(shape1, shape2); m_manifold = m_manifolds[0]; m_manifold.pointCount = 0; } override b2internal function Evaluate(listener:b2ContactListener):void{ var v1:b2Vec2; var v2:b2Vec2; var mp0:b2ManifoldPoint; var cp:b2ContactPoint; var i:int; var mp:b2ManifoldPoint; var found:Boolean; var idKey:uint; var j:int; var b1:b2Body = m_shape1.m_body; var b2:b2Body = m_shape2.m_body; m0.Set(m_manifold); b2Collision.b2CollidePolygons(m_manifold, (m_shape1 as b2PolygonShape), b1.m_xf, (m_shape2 as b2PolygonShape), b2.m_xf); var persisted:Array = [false, false]; cp = s_evalCP; cp.shape1 = m_shape1; cp.shape2 = m_shape2; cp.friction = b2Settings.b2MixFriction(m_shape1.GetFriction(), m_shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(m_shape1.GetRestitution(), m_shape2.GetRestitution()); if (m_manifold.pointCount > 0){ i = 0; while (i < m_manifold.pointCount) { mp = m_manifold.points[i]; mp.normalImpulse = 0; mp.tangentImpulse = 0; found = false; idKey = mp.id._key; j = 0; while (j < m0.pointCount) { if (persisted[j] == true){ } else { mp0 = m0.points[j]; if (mp0.id._key == idKey){ persisted[j] = true; mp.normalImpulse = mp0.normalImpulse; mp.tangentImpulse = mp0.tangentImpulse; found = true; if (listener != null){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Persist(cp); }; break; }; }; j++; }; if ((((found == false)) && (!((listener == null))))){ cp.position = b1.GetWorldPoint(mp.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m_manifold.normal); cp.separation = mp.separation; cp.id.key = idKey; listener.Add(cp); }; i++; }; m_manifoldCount = 1; } else { m_manifoldCount = 0; }; if (listener == null){ return; }; i = 0; while (i < m0.pointCount) { if (persisted[i]){ } else { mp0 = m0.points[i]; cp.position = b1.GetWorldPoint(mp0.localPoint1); v1 = b1.GetLinearVelocityFromLocalPoint(mp0.localPoint1); v2 = b2.GetLinearVelocityFromLocalPoint(mp0.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.normal.SetV(m0.normal); cp.separation = mp0.separation; cp.id.key = mp0.id._key; listener.Remove(cp); }; i++; }; } override public function GetManifolds():Array{ return (m_manifolds); } public static function Destroy(contact:b2Contact, allocator):void{ } public static function Create(shape1:b2Shape, shape2:b2Shape, allocator):b2Contact{ return (new b2PolygonContact(shape1, shape2)); } } }//package Box2D.Dynamics.Contacts
Section 54
//b2Controller (Box2D.Dynamics.Controllers.b2Controller) package Box2D.Dynamics.Controllers { import Box2D.Dynamics.*; import Box2D.Common.*; public class b2Controller { b2internal var m_world:b2World; b2internal var m_prev:b2Controller; b2internal var m_next:b2Controller; protected var m_bodyList:b2ControllerEdge; protected var m_bodyCount:int; public function b2Controller(){ super(); } public function AddBody(body:b2Body):void{ var edge:b2ControllerEdge = new b2ControllerEdge(); edge.controller = this; edge.body = body; edge.nextBody = m_bodyList; edge.prevBody = null; m_bodyList = edge; if (edge.nextBody){ edge.nextBody.prevBody = edge; }; m_bodyCount++; edge.nextController = body.m_controllerList; edge.prevController = null; body.m_controllerList = edge; if (edge.nextController){ edge.nextController.prevController = edge; }; body.m_controllerCount++; } public function Draw(debugDraw:b2DebugDraw):void{ } public function RemoveBody(body:b2Body):void{ var edge:b2ControllerEdge; while (((edge) && (!((edge.controller == this))))) { edge = edge.nextController; }; if (edge.prevBody){ edge.prevBody.nextBody = edge.nextBody; }; if (edge.nextBody){ edge.nextBody.prevBody = edge.prevBody; }; if (edge.nextController){ edge.nextController.prevController = edge.prevController; }; if (edge.prevController){ edge.prevController.nextController = edge.nextController; }; if (m_bodyList == edge){ m_bodyList = edge.nextBody; }; if (body.m_controllerList == edge){ body.m_controllerList = edge.nextController; }; body.m_controllerCount--; m_bodyCount--; } public function GetNext():b2Controller{ return (m_next); } public function Clear():void{ while (m_bodyList) { RemoveBody(m_bodyList.body); }; } public function Step(step:b2TimeStep):void{ } public function GetBodyList():b2ControllerEdge{ return (m_bodyList); } public function GetWorld():b2World{ return (m_world); } } }//package Box2D.Dynamics.Controllers
Section 55
//b2ControllerEdge (Box2D.Dynamics.Controllers.b2ControllerEdge) package Box2D.Dynamics.Controllers { import Box2D.Dynamics.*; public class b2ControllerEdge { public var body:b2Body; public var nextBody:b2ControllerEdge; public var nextController:b2ControllerEdge; public var prevBody:b2ControllerEdge; public var prevController:b2ControllerEdge; public var controller:b2Controller; public function b2ControllerEdge(){ super(); } } }//package Box2D.Dynamics.Controllers
Section 56
//b2DistanceJoint (Box2D.Dynamics.Joints.b2DistanceJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2DistanceJoint extends b2Joint { private var m_localAnchor1:b2Vec2; private var m_localAnchor2:b2Vec2; private var m_bias:Number; private var m_gamma:Number; private var m_u:b2Vec2; private var m_mass:Number; private var m_impulse:Number; private var m_dampingRatio:Number; private var m_frequencyHz:Number; private var m_length:Number; public function b2DistanceJoint(def:b2DistanceJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_u = new b2Vec2(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_length = def.length; m_frequencyHz = def.frequencyHz; m_dampingRatio = def.dampingRatio; m_impulse = 0; m_gamma = 0; m_bias = 0; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var b1:b2Body; var b2:b2Body; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var C:Number; var omega:Number; var d:Number; var k:Number; var PX:Number; var PY:Number; b1 = m_body1; b2 = m_body2; tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; m_u.x = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); m_u.y = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); var length:Number = Math.sqrt(((m_u.x * m_u.x) + (m_u.y * m_u.y))); if (length > b2Settings.b2_linearSlop){ m_u.Multiply((1 / length)); } else { m_u.SetZero(); }; var cr1u:Number = ((r1X * m_u.y) - (r1Y * m_u.x)); var cr2u:Number = ((r2X * m_u.y) - (r2Y * m_u.x)); var invMass:Number = (((b1.m_invMass + ((b1.m_invI * cr1u) * cr1u)) + b2.m_invMass) + ((b2.m_invI * cr2u) * cr2u)); m_mass = (1 / invMass); if (m_frequencyHz > 0){ C = (length - m_length); omega = ((2 * Math.PI) * m_frequencyHz); d = (((2 * m_mass) * m_dampingRatio) * omega); k = ((m_mass * omega) * omega); m_gamma = (1 / (step.dt * (d + (step.dt * k)))); m_bias = (((C * step.dt) * k) * m_gamma); m_mass = (1 / (invMass + m_gamma)); }; if (step.warmStarting){ m_impulse = (m_impulse * step.dtRatio); PX = (m_impulse * m_u.x); PY = (m_impulse * m_u.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (b1.m_invMass * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (b1.m_invMass * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); } else { m_impulse = 0; }; } override public function GetReactionTorque(inv_dt:Number):Number{ return (0); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2(((inv_dt * m_impulse) * m_u.x), ((inv_dt * m_impulse) * m_u.y))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var tMat:b2Mat22; if (m_frequencyHz > 0){ return (true); }; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); var dY:Number = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); var length:Number = Math.sqrt(((dX * dX) + (dY * dY))); dX = (dX / length); dY = (dY / length); var C:Number = (length - m_length); C = b2Math.b2Clamp(C, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); var impulse:Number = (-(m_mass) * C); m_u.Set(dX, dY); var PX:Number = (impulse * m_u.x); var PY:Number = (impulse * m_u.y); b1.m_sweep.c.x = (b1.m_sweep.c.x - (b1.m_invMass * PX)); b1.m_sweep.c.y = (b1.m_sweep.c.y - (b1.m_invMass * PY)); b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * PX)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * PY)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((b2Math.b2Abs(C) < b2Settings.b2_linearSlop)); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var v1X:Number = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); var v1Y:Number = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); var v2X:Number = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); var v2Y:Number = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); var Cdot:Number = ((m_u.x * (v2X - v1X)) + (m_u.y * (v2Y - v1Y))); var impulse:Number = (-(m_mass) * ((Cdot + m_bias) + (m_gamma * m_impulse))); m_impulse = (m_impulse + impulse); var PX:Number = (impulse * m_u.x); var PY:Number = (impulse * m_u.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (b1.m_invMass * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (b1.m_invMass * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (b1.m_invI * ((r1X * PY) - (r1Y * PX)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * PY) - (r2Y * PX)))); } } }//package Box2D.Dynamics.Joints
Section 57
//b2DistanceJointDef (Box2D.Dynamics.Joints.b2DistanceJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class b2DistanceJointDef extends b2JointDef { public var localAnchor1:b2Vec2; public var length:Number; public var dampingRatio:Number; public var localAnchor2:b2Vec2; public var frequencyHz:Number; public function b2DistanceJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_distanceJoint; length = 1; frequencyHz = 0; dampingRatio = 0; } public function Initialize(b1:b2Body, b2:b2Body, anchor1:b2Vec2, anchor2:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1.SetV(body1.GetLocalPoint(anchor1)); localAnchor2.SetV(body2.GetLocalPoint(anchor2)); var dX:Number = (anchor2.x - anchor1.x); var dY:Number = (anchor2.y - anchor1.y); length = Math.sqrt(((dX * dX) + (dY * dY))); frequencyHz = 0; dampingRatio = 0; } } }//package Box2D.Dynamics.Joints
Section 58
//b2GearJoint (Box2D.Dynamics.Joints.b2GearJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2GearJoint extends b2Joint { private var m_ground2:b2Body; private var m_groundAnchor1:b2Vec2; private var m_groundAnchor2:b2Vec2; private var m_localAnchor1:b2Vec2; private var m_localAnchor2:b2Vec2; private var m_ratio:Number; private var m_revolute2:b2RevoluteJoint; private var m_mass:Number; private var m_impulse:Number; private var m_prismatic2:b2PrismaticJoint; private var m_ground1:b2Body; private var m_revolute1:b2RevoluteJoint; private var m_prismatic1:b2PrismaticJoint; private var m_constant:Number; private var m_J:b2Jacobian; public function b2GearJoint(def:b2GearJointDef){ var coordinate1:Number; var coordinate2:Number; m_groundAnchor1 = new b2Vec2(); m_groundAnchor2 = new b2Vec2(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_J = new b2Jacobian(); super(def); var type1:int = def.joint1.m_type; var type2:int = def.joint2.m_type; m_revolute1 = null; m_prismatic1 = null; m_revolute2 = null; m_prismatic2 = null; m_ground1 = def.joint1.m_body1; m_body1 = def.joint1.m_body2; if (type1 == b2Joint.e_revoluteJoint){ m_revolute1 = (def.joint1 as b2RevoluteJoint); m_groundAnchor1.SetV(m_revolute1.m_localAnchor1); m_localAnchor1.SetV(m_revolute1.m_localAnchor2); coordinate1 = m_revolute1.GetJointAngle(); } else { m_prismatic1 = (def.joint1 as b2PrismaticJoint); m_groundAnchor1.SetV(m_prismatic1.m_localAnchor1); m_localAnchor1.SetV(m_prismatic1.m_localAnchor2); coordinate1 = m_prismatic1.GetJointTranslation(); }; m_ground2 = def.joint2.m_body1; m_body2 = def.joint2.m_body2; if (type2 == b2Joint.e_revoluteJoint){ m_revolute2 = (def.joint2 as b2RevoluteJoint); m_groundAnchor2.SetV(m_revolute2.m_localAnchor1); m_localAnchor2.SetV(m_revolute2.m_localAnchor2); coordinate2 = m_revolute2.GetJointAngle(); } else { m_prismatic2 = (def.joint2 as b2PrismaticJoint); m_groundAnchor2.SetV(m_prismatic2.m_localAnchor1); m_localAnchor2.SetV(m_prismatic2.m_localAnchor2); coordinate2 = m_prismatic2.GetJointTranslation(); }; m_ratio = def.ratio; m_constant = (coordinate1 + (m_ratio * coordinate2)); m_impulse = 0; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var ugX:Number; var ugY:Number; var rX:Number; var rY:Number; var tMat:b2Mat22; var tVec:b2Vec2; var crug:Number; var tX:Number; var g1:b2Body = m_ground1; var g2:b2Body = m_ground2; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var K:Number = 0; m_J.SetZero(); if (m_revolute1){ m_J.angular1 = -1; K = (K + b1.m_invI); } else { tMat = g1.m_xf.R; tVec = m_prismatic1.m_localXAxis1; ugX = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); ugY = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = b1.m_xf.R; rX = (m_localAnchor1.x - b1.m_sweep.localCenter.x); rY = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; crug = ((rX * ugY) - (rY * ugX)); m_J.linear1.Set(-(ugX), -(ugY)); m_J.angular1 = -(crug); K = (K + (b1.m_invMass + ((b1.m_invI * crug) * crug))); }; if (m_revolute2){ m_J.angular2 = -(m_ratio); K = (K + ((m_ratio * m_ratio) * b2.m_invI)); } else { tMat = g2.m_xf.R; tVec = m_prismatic2.m_localXAxis1; ugX = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); ugY = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); tMat = b2.m_xf.R; rX = (m_localAnchor2.x - b2.m_sweep.localCenter.x); rY = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; crug = ((rX * ugY) - (rY * ugX)); m_J.linear2.Set((-(m_ratio) * ugX), (-(m_ratio) * ugY)); m_J.angular2 = (-(m_ratio) * crug); K = (K + ((m_ratio * m_ratio) * (b2.m_invMass + ((b2.m_invI * crug) * crug)))); }; m_mass = (1 / K); if (step.warmStarting){ b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((b1.m_invMass * m_impulse) * m_J.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((b1.m_invMass * m_impulse) * m_J.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((b1.m_invI * m_impulse) * m_J.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((b2.m_invMass * m_impulse) * m_J.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((b2.m_invMass * m_impulse) * m_J.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * m_impulse) * m_J.angular2)); } else { m_impulse = 0; }; } override public function GetReactionTorque(inv_dt:Number):Number{ var tMat:b2Mat22 = m_body2.m_xf.R; var rX:Number = (m_localAnchor1.x - m_body2.m_sweep.localCenter.x); var rY:Number = (m_localAnchor1.y - m_body2.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; var PX:Number = (m_impulse * m_J.linear2.x); var PY:Number = (m_impulse * m_J.linear2.y); return ((inv_dt * (((m_impulse * m_J.angular2) - (rX * PY)) + (rY * PX)))); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2(((inv_dt * m_impulse) * m_J.linear2.x), ((inv_dt * m_impulse) * m_J.linear2.y))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var coordinate1:Number; var coordinate2:Number; var linearError:Number = 0; var b1:b2Body = m_body1; var b2:b2Body = m_body2; if (m_revolute1){ coordinate1 = m_revolute1.GetJointAngle(); } else { coordinate1 = m_prismatic1.GetJointTranslation(); }; if (m_revolute2){ coordinate2 = m_revolute2.GetJointAngle(); } else { coordinate2 = m_prismatic2.GetJointTranslation(); }; var C:Number = (m_constant - (coordinate1 + (m_ratio * coordinate2))); var impulse:Number = (-(m_mass) * C); b1.m_sweep.c.x = (b1.m_sweep.c.x + ((b1.m_invMass * impulse) * m_J.linear1.x)); b1.m_sweep.c.y = (b1.m_sweep.c.y + ((b1.m_invMass * impulse) * m_J.linear1.y)); b1.m_sweep.a = (b1.m_sweep.a + ((b1.m_invI * impulse) * m_J.angular1)); b2.m_sweep.c.x = (b2.m_sweep.c.x + ((b2.m_invMass * impulse) * m_J.linear2.x)); b2.m_sweep.c.y = (b2.m_sweep.c.y + ((b2.m_invMass * impulse) * m_J.linear2.y)); b2.m_sweep.a = (b2.m_sweep.a + ((b2.m_invI * impulse) * m_J.angular2)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((linearError < b2Settings.b2_linearSlop)); } public function GetRatio():Number{ return (m_ratio); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var Cdot:Number = m_J.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); var impulse:Number = (-(m_mass) * Cdot); m_impulse = (m_impulse + impulse); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + ((b1.m_invMass * impulse) * m_J.linear1.x)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + ((b1.m_invMass * impulse) * m_J.linear1.y)); b1.m_angularVelocity = (b1.m_angularVelocity + ((b1.m_invI * impulse) * m_J.angular1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + ((b2.m_invMass * impulse) * m_J.linear2.x)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + ((b2.m_invMass * impulse) * m_J.linear2.y)); b2.m_angularVelocity = (b2.m_angularVelocity + ((b2.m_invI * impulse) * m_J.angular2)); } } }//package Box2D.Dynamics.Joints
Section 59
//b2GearJointDef (Box2D.Dynamics.Joints.b2GearJointDef) package Box2D.Dynamics.Joints { public class b2GearJointDef extends b2JointDef { public var joint1:b2Joint; public var joint2:b2Joint; public var ratio:Number; public function b2GearJointDef(){ super(); type = b2Joint.e_gearJoint; joint1 = null; joint2 = null; ratio = 1; } } }//package Box2D.Dynamics.Joints
Section 60
//b2Jacobian (Box2D.Dynamics.Joints.b2Jacobian) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; public class b2Jacobian { public var linear1:b2Vec2; public var linear2:b2Vec2; public var angular1:Number; public var angular2:Number; public function b2Jacobian(){ linear1 = new b2Vec2(); linear2 = new b2Vec2(); super(); } public function Set(x1:b2Vec2, a1:Number, x2:b2Vec2, a2:Number):void{ linear1.SetV(x1); angular1 = a1; linear2.SetV(x2); angular2 = a2; } public function SetZero():void{ linear1.SetZero(); angular1 = 0; linear2.SetZero(); angular2 = 0; } public function Compute(x1:b2Vec2, a1:Number, x2:b2Vec2, a2:Number):Number{ return ((((((linear1.x * x1.x) + (linear1.y * x1.y)) + (angular1 * a1)) + ((linear2.x * x2.x) + (linear2.y * x2.y))) + (angular2 * a2))); } } }//package Box2D.Dynamics.Joints
Section 61
//b2Joint (Box2D.Dynamics.Joints.b2Joint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2Joint { b2internal var m_islandFlag:Boolean; b2internal var m_collideConnected:Boolean; b2internal var m_prev:b2Joint; b2internal var m_type:int; b2internal var m_next:b2Joint; b2internal var m_node1:b2JointEdge; b2internal var m_node2:b2JointEdge; b2internal var m_localCenter1:b2Vec2; b2internal var m_localCenter2:b2Vec2; b2internal var m_invMass1:Number; b2internal var m_invI2:Number; b2internal var m_invMass2:Number; private var m_userData; b2internal var m_body1:b2Body; b2internal var m_body2:b2Body; b2internal var m_invI1:Number; b2internal static const e_prismaticJoint:int = 2; b2internal static const e_equalLimits:int = 3; b2internal static const e_lineJoint:int = 7; b2internal static const e_gearJoint:int = 6; b2internal static const e_atUpperLimit:int = 2; b2internal static const e_atLowerLimit:int = 1; b2internal static const e_revoluteJoint:int = 1; b2internal static const e_inactiveLimit:int = 0; b2internal static const e_pulleyJoint:int = 4; b2internal static const e_unknownJoint:int = 0; b2internal static const e_distanceJoint:int = 3; b2internal static const e_mouseJoint:int = 5; public function b2Joint(def:b2JointDef){ m_node1 = new b2JointEdge(); m_node2 = new b2JointEdge(); m_localCenter1 = new b2Vec2(); m_localCenter2 = new b2Vec2(); super(); m_type = def.type; m_prev = null; m_next = null; m_body1 = def.body1; m_body2 = def.body2; m_collideConnected = def.collideConnected; m_islandFlag = false; m_userData = def.userData; } public function GetBody2():b2Body{ return (m_body2); } b2internal function ComputeXForm(xf:b2XForm, center:b2Vec2, localCenter:b2Vec2, angle:Number):void{ xf.R.Set(angle); xf.position.SetV(b2Math.SubtractVV(center, b2Math.b2MulMV(xf.R, localCenter))); } public function GetAnchor1():b2Vec2{ return (null); } public function GetAnchor2():b2Vec2{ return (null); } public function GetNext():b2Joint{ return (m_next); } public function GetType():int{ return (m_type); } b2internal function InitVelocityConstraints(step:b2TimeStep):void{ } public function GetReactionTorque(inv_dt:Number):Number{ return (0); } public function GetUserData(){ return (m_userData); } public function GetReactionForce(inv_dt:Number):b2Vec2{ return (null); } b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ return (false); } public function SetUserData(data):void{ m_userData = data; } public function GetBody1():b2Body{ return (m_body1); } b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ } b2internal static function Destroy(joint:b2Joint, allocator):void{ } b2internal static function Create(def:b2JointDef, allocator):b2Joint{ var joint:b2Joint; switch (def.type){ case e_distanceJoint: joint = new b2DistanceJoint((def as b2DistanceJointDef)); break; case e_mouseJoint: joint = new b2MouseJoint((def as b2MouseJointDef)); break; case e_prismaticJoint: joint = new b2PrismaticJoint((def as b2PrismaticJointDef)); break; case e_revoluteJoint: joint = new b2RevoluteJoint((def as b2RevoluteJointDef)); break; case e_pulleyJoint: joint = new b2PulleyJoint((def as b2PulleyJointDef)); break; case e_gearJoint: joint = new b2GearJoint((def as b2GearJointDef)); break; case e_lineJoint: joint = new b2LineJoint((def as b2LineJointDef)); break; default: break; }; return (joint); } } }//package Box2D.Dynamics.Joints
Section 62
//b2JointDef (Box2D.Dynamics.Joints.b2JointDef) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; public class b2JointDef { public var body2:b2Body; public var type:int; public var userData; public var collideConnected:Boolean; public var body1:b2Body; public function b2JointDef(){ super(); type = b2Joint.e_unknownJoint; userData = null; body1 = null; body2 = null; collideConnected = false; } } }//package Box2D.Dynamics.Joints
Section 63
//b2JointEdge (Box2D.Dynamics.Joints.b2JointEdge) package Box2D.Dynamics.Joints { import Box2D.Dynamics.*; public class b2JointEdge { public var other:b2Body; public var next:b2JointEdge; public var prev:b2JointEdge; public var joint:b2Joint; public function b2JointEdge(){ super(); } } }//package Box2D.Dynamics.Joints
Section 64
//b2LineJoint (Box2D.Dynamics.Joints.b2LineJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2LineJoint extends b2Joint { private var m_a1:Number; private var m_a2:Number; private var m_perp:b2Vec2; private var m_lowerTranslation:Number; b2internal var m_localXAxis1:b2Vec2; private var m_impulse:b2Vec2; private var m_enableLimit:Boolean; private var m_maxMotorForce:Number; private var m_localYAxis1:b2Vec2; private var m_s2:Number; private var m_axis:b2Vec2; private var m_motorMass:Number; private var m_s1:Number; private var m_upperTranslation:Number; b2internal var m_localAnchor1:b2Vec2; b2internal var m_localAnchor2:b2Vec2; private var m_limitState:int; private var m_motorImpulse:Number; private var m_motorSpeed:Number; private var m_enableMotor:Boolean; private var m_K:b2Mat22; public function b2LineJoint(def:b2LineJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_localXAxis1 = new b2Vec2(); m_localYAxis1 = new b2Vec2(); m_axis = new b2Vec2(); m_perp = new b2Vec2(); m_K = new b2Mat22(); m_impulse = new b2Vec2(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_localXAxis1.SetV(def.localAxis1); m_localYAxis1.x = -(m_localXAxis1.y); m_localYAxis1.y = m_localXAxis1.x; m_impulse.SetZero(); m_motorMass = 0; m_motorImpulse = 0; m_lowerTranslation = def.lowerTranslation; m_upperTranslation = def.upperTranslation; m_maxMotorForce = def.maxMotorForce; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; m_limitState = e_inactiveLimit; m_axis.SetZero(); m_perp.SetZero(); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var PX:Number; var PY:Number; var L1:Number; var L2:Number; var Cdot:Number; var impulse:Number; var oldImpulse:Number; var maxImpulse:Number; var Cdot2:Number; var f1:b2Vec2; var df:b2Vec2; var b:Number; var f2r:Number; var df2:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var v1:b2Vec2 = b1.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w2:Number = b2.m_angularVelocity; if (((m_enableMotor) && (!((m_limitState == e_equalLimits))))){ Cdot = ((((m_axis.x * (v2.x - v1.x)) + (m_axis.y * (v2.y - v1.y))) + (m_a2 * w2)) - (m_a1 * w1)); impulse = (m_motorMass * (m_motorSpeed - Cdot)); oldImpulse = m_motorImpulse; maxImpulse = (step.dt * m_maxMotorForce); m_motorImpulse = b2Math.b2Clamp((m_motorImpulse + impulse), -(maxImpulse), maxImpulse); impulse = (m_motorImpulse - oldImpulse); PX = (impulse * m_axis.x); PY = (impulse * m_axis.y); L1 = (impulse * m_a1); L2 = (impulse * m_a2); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); }; var Cdot1:Number = ((((m_perp.x * (v2.x - v1.x)) + (m_perp.y * (v2.y - v1.y))) + (m_s2 * w2)) - (m_s1 * w1)); if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ Cdot2 = ((((m_axis.x * (v2.x - v1.x)) + (m_axis.y * (v2.y - v1.y))) + (m_a2 * w2)) - (m_a1 * w1)); f1 = m_impulse.Copy(); df = m_K.Solve(new b2Vec2(), -(Cdot1), -(Cdot2)); m_impulse.Add(df); if (m_limitState == e_atLowerLimit){ m_impulse.y = b2Math.b2Max(m_impulse.y, 0); } else { if (m_limitState == e_atUpperLimit){ m_impulse.y = b2Math.b2Min(m_impulse.y, 0); }; }; b = (-(Cdot1) - ((m_impulse.y - f1.y) * m_K.col2.x)); f2r = ((b / m_K.col1.x) + f1.x); m_impulse.x = f2r; df.x = (m_impulse.x - f1.x); df.y = (m_impulse.y - f1.y); PX = ((df.x * m_perp.x) + (df.y * m_axis.x)); PY = ((df.x * m_perp.y) + (df.y * m_axis.y)); L1 = ((df.x * m_s1) + (df.y * m_a1)); L2 = ((df.x * m_s2) + (df.y * m_a2)); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); } else { df2 = (-(Cdot1) / m_K.col1.x); m_impulse.x = (m_impulse.x + df2); PX = (df2 * m_perp.x); PY = (df2 * m_perp.y); L1 = (df2 * m_s1); L2 = (df2 * m_s2); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); }; b1.m_linearVelocity.SetV(v1); b1.m_angularVelocity = w1; b2.m_linearVelocity.SetV(v2); b2.m_angularVelocity = w2; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } public function GetUpperLimit():Number{ return (m_upperTranslation); } public function GetLowerLimit():Number{ return (m_lowerTranslation); } public function EnableMotor(flag:Boolean):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_enableMotor = flag; } public function GetJointTranslation():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var p1:b2Vec2 = b1.GetWorldPoint(m_localAnchor1); var p2:b2Vec2 = b2.GetWorldPoint(m_localAnchor2); var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var translation:Number = ((axis.x * dX) + (axis.y * dY)); return (translation); } public function GetMotorSpeed():Number{ return (m_motorSpeed); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2((inv_dt * ((m_impulse.x * m_perp.x) + ((m_motorImpulse + m_impulse.y) * m_axis.x))), (inv_dt * ((m_impulse.x * m_perp.y) + ((m_motorImpulse + m_impulse.y) * m_axis.y))))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var limitC:Number; var oldLimitImpulse:Number; var tMat:b2Mat22; var tX:Number; var m1:Number; var m2:Number; var i1:Number; var i2:Number; var translation:Number; var k11:Number; var impulse1:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var c1:b2Vec2 = b1.m_sweep.c; var a1:Number = b1.m_sweep.a; var c2:b2Vec2 = b2.m_sweep.c; var a2:Number = b2.m_sweep.a; var linearError:Number = 0; var angularError:Number = 0; var active:Boolean; var C2:Number = 0; var R1:b2Mat22 = new b2Mat22(a1); var R2:b2Mat22 = new b2Mat22(a2); tMat = R1; var r1X:Number = (m_localAnchor1.x - m_localCenter1.x); var r1Y:Number = (m_localAnchor1.y - m_localCenter1.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = R2; var r2X:Number = (m_localAnchor2.x - m_localCenter2.x); var r2Y:Number = (m_localAnchor2.y - m_localCenter2.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((c2.x + r2X) - c1.x) - r1X); var dY:Number = (((c2.y + r2Y) - c1.y) - r1Y); if (m_enableLimit){ m_axis = b2Math.b2MulMV(R1, m_localXAxis1); m_a1 = (((dX + r1X) * m_axis.y) - ((dY + r1Y) * m_axis.x)); m_a2 = ((r2X * m_axis.y) - (r2Y * m_axis.x)); translation = ((m_axis.x * dX) + (m_axis.y * dY)); if (b2Math.b2Abs((m_upperTranslation - m_lowerTranslation)) < (2 * b2Settings.b2_linearSlop)){ C2 = b2Math.b2Clamp(translation, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); linearError = b2Math.b2Abs(translation); active = true; } else { if (translation <= m_lowerTranslation){ C2 = b2Math.b2Clamp(((translation - m_lowerTranslation) + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); linearError = (m_lowerTranslation - translation); active = true; } else { if (translation >= m_upperTranslation){ C2 = b2Math.b2Clamp(((translation - m_upperTranslation) + b2Settings.b2_linearSlop), 0, b2Settings.b2_maxLinearCorrection); linearError = (translation - m_upperTranslation); active = true; }; }; }; }; m_perp = b2Math.b2MulMV(R1, m_localYAxis1); m_s1 = (((dX + r1X) * m_perp.y) - ((dY + r1Y) * m_perp.x)); m_s2 = ((r2X * m_perp.y) - (r2Y * m_perp.x)); var impulse:b2Vec2 = new b2Vec2(); var C1:Number = ((m_perp.x * dX) + (m_perp.y * dY)); linearError = b2Math.b2Max(linearError, b2Math.b2Abs(C1)); angularError = 0; if (active){ m1 = m_invMass1; m2 = m_invMass2; i1 = m_invI1; i2 = m_invI2; m_K.col1.x = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); m_K.col1.y = (((i1 * m_s1) * m_a1) + ((i2 * m_s2) * m_a2)); m_K.col2.x = m_K.col1.y; m_K.col2.y = (((m1 + m2) + ((i1 * m_a1) * m_a1)) + ((i2 * m_a2) * m_a2)); m_K.Solve(impulse, -(C1), -(C2)); } else { m1 = m_invMass1; m2 = m_invMass2; i1 = m_invI1; i2 = m_invI2; k11 = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); impulse1 = (-(C1) / k11); impulse.x = impulse1; impulse.y = 0; }; var PX:Number = ((impulse.x * m_perp.x) + (impulse.y * m_axis.x)); var PY:Number = ((impulse.x * m_perp.y) + (impulse.y * m_axis.y)); var L1:Number = ((impulse.x * m_s1) + (impulse.y * m_a1)); var L2:Number = ((impulse.x * m_s2) + (impulse.y * m_a2)); c1.x = (c1.x - (m_invMass1 * PX)); c1.y = (c1.y - (m_invMass1 * PY)); a1 = (a1 - (m_invI1 * L1)); c2.x = (c2.x + (m_invMass2 * PX)); c2.y = (c2.y + (m_invMass2 * PY)); a2 = (a2 + (m_invI2 * L2)); b1.m_sweep.a = a1; b2.m_sweep.a = a2; b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((((linearError <= b2Settings.b2_linearSlop)) && ((angularError <= b2Settings.b2_angularSlop)))); } public function SetMotorSpeed(speed:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_motorSpeed = speed; } public function GetJointSpeed():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var v1:b2Vec2 = b1.m_linearVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var w2:Number = b2.m_angularVelocity; var speed:Number = (((dX * (-(w1) * axis.y)) + (dY * (w1 * axis.x))) + ((axis.x * (((v2.x + (-(w2) * r2Y)) - v1.x) - (-(w1) * r1Y))) + (axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X))))); return (speed); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var jointTransition:Number; var PX:Number; var PY:Number; var L1:Number; var L2:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; m_localCenter1.SetV(b1.GetLocalCenter()); m_localCenter2.SetV(b2.GetLocalCenter()); var xf1:b2XForm = b1.GetXForm(); var xf2:b2XForm = b2.GetXForm(); tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); var dY:Number = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); m_invMass1 = b1.m_invMass; m_invMass2 = b2.m_invMass; m_invI1 = b1.m_invI; m_invI2 = b2.m_invI; m_axis.SetV(b2Math.b2MulMV(xf1.R, m_localXAxis1)); m_a1 = (((dX + r1X) * m_axis.y) - ((dY + r1Y) * m_axis.x)); m_a2 = ((r2X * m_axis.y) - (r2Y * m_axis.x)); m_motorMass = (((m_invMass1 + m_invMass2) + ((m_invI1 * m_a1) * m_a1)) + ((m_invI2 * m_a2) * m_a2)); m_motorMass = (1 / m_motorMass); m_perp.SetV(b2Math.b2MulMV(xf1.R, m_localYAxis1)); m_s1 = (((dX + r1X) * m_perp.y) - ((dY + r1Y) * m_perp.x)); m_s2 = ((r2X * m_perp.y) - (r2Y * m_perp.x)); var m1:Number = m_invMass1; var m2:Number = m_invMass2; var i1:Number = m_invI1; var i2:Number = m_invI2; m_K.col1.x = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); m_K.col1.y = (((i1 * m_s1) * m_a1) + ((i2 * m_s2) * m_a2)); m_K.col2.x = m_K.col1.y; m_K.col2.y = (((m1 + m2) + ((i1 * m_a1) * m_a1)) + ((i2 * m_a2) * m_a2)); if (m_enableLimit){ jointTransition = ((m_axis.x * dX) + (m_axis.y * dY)); if (b2Math.b2Abs((m_upperTranslation - m_lowerTranslation)) < (2 * b2Settings.b2_linearSlop)){ m_limitState = e_equalLimits; } else { if (jointTransition <= m_lowerTranslation){ if (m_limitState != e_atLowerLimit){ m_limitState = e_atLowerLimit; m_impulse.y = 0; }; } else { if (jointTransition >= m_upperTranslation){ if (m_limitState != e_atUpperLimit){ m_limitState = e_atUpperLimit; m_impulse.y = 0; }; } else { m_limitState = e_inactiveLimit; m_impulse.y = 0; }; }; }; } else { m_limitState = e_inactiveLimit; }; if (m_enableMotor == false){ m_motorImpulse = 0; }; if (step.warmStarting){ m_impulse.x = (m_impulse.x * step.dtRatio); m_impulse.y = (m_impulse.y * step.dtRatio); m_motorImpulse = (m_motorImpulse * step.dtRatio); PX = ((m_impulse.x * m_perp.x) + ((m_motorImpulse + m_impulse.y) * m_axis.x)); PY = ((m_impulse.x * m_perp.y) + ((m_motorImpulse + m_impulse.y) * m_axis.y)); L1 = ((m_impulse.x * m_s1) + ((m_motorImpulse + m_impulse.y) * m_a1)); L2 = ((m_impulse.x * m_s2) + ((m_motorImpulse + m_impulse.y) * m_a2)); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (m_invMass1 * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (m_invMass1 * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (m_invI1 * L1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (m_invMass2 * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (m_invMass2 * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (m_invI2 * L2)); } else { m_impulse.SetZero(); m_motorImpulse = 0; }; } public function GetMotorForce():Number{ return (m_motorImpulse); } public function EnableLimit(flag:Boolean):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_enableLimit = flag; } public function SetMaxMotorForce(force:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_maxMotorForce = force; } override public function GetReactionTorque(inv_dt:Number):Number{ return ((inv_dt * m_impulse.y)); } public function IsLimitEnabled():Boolean{ return (m_enableLimit); } public function IsMotorEnabled():Boolean{ return (m_enableMotor); } public function SetLimits(lower:Number, upper:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_lowerTranslation = lower; m_upperTranslation = upper; } } }//package Box2D.Dynamics.Joints
Section 65
//b2LineJointDef (Box2D.Dynamics.Joints.b2LineJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class b2LineJointDef extends b2JointDef { public var motorSpeed:Number; public var localAxis1:b2Vec2; public var upperTranslation:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var enableLimit:Boolean; public var enableMotor:Boolean; public var maxMotorForce:Number; public var lowerTranslation:Number; public function b2LineJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); localAxis1 = new b2Vec2(); super(); type = b2Joint.e_lineJoint; localAxis1.Set(1, 0); enableLimit = false; lowerTranslation = 0; upperTranslation = 0; enableMotor = false; maxMotorForce = 0; motorSpeed = 0; } public function Initialize(b1:b2Body, b2:b2Body, anchor:b2Vec2, axis:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1 = body1.GetLocalPoint(anchor); localAnchor2 = body2.GetLocalPoint(anchor); localAxis1 = body1.GetLocalVector(axis); } } }//package Box2D.Dynamics.Joints
Section 66
//b2MouseJoint (Box2D.Dynamics.Joints.b2MouseJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2MouseJoint extends b2Joint { private var K1:b2Mat22; private var K:b2Mat22; private var m_beta:Number; private var m_mass:b2Mat22; private var K2:b2Mat22; private var m_target:b2Vec2; private var m_gamma:Number; private var m_impulse:b2Vec2; private var m_C:b2Vec2; private var m_localAnchor:b2Vec2; private var m_maxForce:Number; private var m_dampingRatio:Number; private var m_frequencyHz:Number; public function b2MouseJoint(def:b2MouseJointDef){ var tY:Number; K = new b2Mat22(); K1 = new b2Mat22(); K2 = new b2Mat22(); m_localAnchor = new b2Vec2(); m_target = new b2Vec2(); m_impulse = new b2Vec2(); m_mass = new b2Mat22(); m_C = new b2Vec2(); super(def); m_target.SetV(def.target); var tX:Number = (m_target.x - m_body2.m_xf.position.x); tY = (m_target.y - m_body2.m_xf.position.y); var tMat:b2Mat22 = m_body2.m_xf.R; m_localAnchor.x = ((tX * tMat.col1.x) + (tY * tMat.col1.y)); m_localAnchor.y = ((tX * tMat.col2.x) + (tY * tMat.col2.y)); m_maxForce = def.maxForce; m_impulse.SetZero(); m_frequencyHz = def.frequencyHz; m_dampingRatio = def.dampingRatio; m_beta = 0; m_gamma = 0; } public function SetTarget(target:b2Vec2):void{ if (m_body2.IsSleeping()){ m_body2.WakeUp(); }; m_target = target; } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor)); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var b:b2Body; var tMat:b2Mat22; var rX:Number; var rY:Number; b = m_body2; var mass:Number = b.GetMass(); var omega:Number = ((2 * Math.PI) * m_frequencyHz); var d:Number = (((2 * mass) * m_dampingRatio) * omega); var k:Number = ((mass * omega) * omega); m_gamma = (1 / (step.dt * (d + (step.dt * k)))); m_beta = ((step.dt * k) * m_gamma); tMat = b.m_xf.R; rX = (m_localAnchor.x - b.m_sweep.localCenter.x); rY = (m_localAnchor.y - b.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; var invMass:Number = b.m_invMass; var invI:Number = b.m_invI; K1.col1.x = invMass; K1.col2.x = 0; K1.col1.y = 0; K1.col2.y = invMass; K2.col1.x = ((invI * rY) * rY); K2.col2.x = ((-(invI) * rX) * rY); K2.col1.y = ((-(invI) * rX) * rY); K2.col2.y = ((invI * rX) * rX); K.SetM(K1); K.AddM(K2); K.col1.x = (K.col1.x + m_gamma); K.col2.y = (K.col2.y + m_gamma); K.GetInverse(m_mass); m_C.x = ((b.m_sweep.c.x + rX) - m_target.x); m_C.y = ((b.m_sweep.c.y + rY) - m_target.y); b.m_angularVelocity = (b.m_angularVelocity * 0.98); m_impulse.x = (m_impulse.x * step.dtRatio); m_impulse.y = (m_impulse.y * step.dtRatio); b.m_linearVelocity.x = (b.m_linearVelocity.x + (invMass * m_impulse.x)); b.m_linearVelocity.y = (b.m_linearVelocity.y + (invMass * m_impulse.y)); b.m_angularVelocity = (b.m_angularVelocity + (invI * ((rX * m_impulse.y) - (rY * m_impulse.x)))); } override public function GetAnchor1():b2Vec2{ return (m_target); } override public function GetReactionTorque(inv_dt:Number):Number{ return (0); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2((inv_dt * m_impulse.x), (inv_dt * m_impulse.y))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ return (true); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var tY:Number; var b:b2Body = m_body2; tMat = b.m_xf.R; var rX:Number = (m_localAnchor.x - b.m_sweep.localCenter.x); var rY:Number = (m_localAnchor.y - b.m_sweep.localCenter.y); tX = ((tMat.col1.x * rX) + (tMat.col2.x * rY)); rY = ((tMat.col1.y * rX) + (tMat.col2.y * rY)); rX = tX; var CdotX:Number = (b.m_linearVelocity.x + (-(b.m_angularVelocity) * rY)); var CdotY:Number = (b.m_linearVelocity.y + (b.m_angularVelocity * rX)); tMat = m_mass; tX = ((CdotX + (m_beta * m_C.x)) + (m_gamma * m_impulse.x)); tY = ((CdotY + (m_beta * m_C.y)) + (m_gamma * m_impulse.y)); var impulseX:Number = -(((tMat.col1.x * tX) + (tMat.col2.x * tY))); var impulseY:Number = -(((tMat.col1.y * tX) + (tMat.col2.y * tY))); var oldImpulseX:Number = m_impulse.x; var oldImpulseY:Number = m_impulse.y; m_impulse.x = (m_impulse.x + impulseX); m_impulse.y = (m_impulse.y + impulseY); var maxImpulse:Number = (step.dt * m_maxForce); if (m_impulse.LengthSquared() > (maxImpulse * maxImpulse)){ m_impulse.Multiply((maxImpulse / m_impulse.Length())); }; impulseX = (m_impulse.x - oldImpulseX); impulseY = (m_impulse.y - oldImpulseY); b.m_linearVelocity.x = (b.m_linearVelocity.x + (b.m_invMass * impulseX)); b.m_linearVelocity.y = (b.m_linearVelocity.y + (b.m_invMass * impulseY)); b.m_angularVelocity = (b.m_angularVelocity + (b.m_invI * ((rX * impulseY) - (rY * impulseX)))); } } }//package Box2D.Dynamics.Joints
Section 67
//b2MouseJointDef (Box2D.Dynamics.Joints.b2MouseJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; public class b2MouseJointDef extends b2JointDef { public var target:b2Vec2; public var maxForce:Number; public var dampingRatio:Number; public var frequencyHz:Number; public function b2MouseJointDef(){ target = new b2Vec2(); super(); type = b2Joint.e_mouseJoint; maxForce = 0; frequencyHz = 5; dampingRatio = 0.7; } } }//package Box2D.Dynamics.Joints
Section 68
//b2PrismaticJoint (Box2D.Dynamics.Joints.b2PrismaticJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2PrismaticJoint extends b2Joint { private var m_a1:Number; private var m_a2:Number; private var m_perp:b2Vec2; private var m_lowerTranslation:Number; b2internal var m_localXAxis1:b2Vec2; private var m_refAngle:Number; private var m_impulse:b2Vec3; private var m_enableLimit:Boolean; private var m_maxMotorForce:Number; private var m_localYAxis1:b2Vec2; private var m_s2:Number; private var m_axis:b2Vec2; private var m_motorMass:Number; private var m_s1:Number; private var m_upperTranslation:Number; b2internal var m_localAnchor1:b2Vec2; b2internal var m_localAnchor2:b2Vec2; private var m_limitState:int; private var m_motorImpulse:Number; private var m_motorSpeed:Number; private var m_enableMotor:Boolean; private var m_K:b2Mat33; public function b2PrismaticJoint(def:b2PrismaticJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_localXAxis1 = new b2Vec2(); m_localYAxis1 = new b2Vec2(); m_axis = new b2Vec2(); m_perp = new b2Vec2(); m_K = new b2Mat33(); m_impulse = new b2Vec3(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_localXAxis1.SetV(def.localAxis1); m_localYAxis1.x = -(m_localXAxis1.y); m_localYAxis1.y = m_localXAxis1.x; m_refAngle = def.referenceAngle; m_impulse.SetZero(); m_motorMass = 0; m_motorImpulse = 0; m_lowerTranslation = def.lowerTranslation; m_upperTranslation = def.upperTranslation; m_maxMotorForce = def.maxMotorForce; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; m_limitState = e_inactiveLimit; m_axis.SetZero(); m_perp.SetZero(); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var PX:Number; var PY:Number; var L1:Number; var L2:Number; var Cdot:Number; var impulse:Number; var oldImpulse:Number; var maxImpulse:Number; var Cdot2:Number; var f1:b2Vec3; var df:b2Vec3; var bX:Number; var bY:Number; var f2r:b2Vec2; var df2:b2Vec2; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var v1:b2Vec2 = b1.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w2:Number = b2.m_angularVelocity; if (((m_enableMotor) && (!((m_limitState == e_equalLimits))))){ Cdot = ((((m_axis.x * (v2.x - v1.x)) + (m_axis.y * (v2.y - v1.y))) + (m_a2 * w2)) - (m_a1 * w1)); impulse = (m_motorMass * (m_motorSpeed - Cdot)); oldImpulse = m_motorImpulse; maxImpulse = (step.dt * m_maxMotorForce); m_motorImpulse = b2Math.b2Clamp((m_motorImpulse + impulse), -(maxImpulse), maxImpulse); impulse = (m_motorImpulse - oldImpulse); PX = (impulse * m_axis.x); PY = (impulse * m_axis.y); L1 = (impulse * m_a1); L2 = (impulse * m_a2); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); }; var Cdot1X:Number = ((((m_perp.x * (v2.x - v1.x)) + (m_perp.y * (v2.y - v1.y))) + (m_s2 * w2)) - (m_s1 * w1)); var Cdot1Y:Number = (w2 - w1); if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ Cdot2 = ((((m_axis.x * (v2.x - v1.x)) + (m_axis.y * (v2.y - v1.y))) + (m_a2 * w2)) - (m_a1 * w1)); f1 = m_impulse.Copy(); df = m_K.Solve33(new b2Vec3(), -(Cdot1X), -(Cdot1Y), -(Cdot2)); m_impulse.Add(df); if (m_limitState == e_atLowerLimit){ m_impulse.z = b2Math.b2Max(m_impulse.z, 0); } else { if (m_limitState == e_atUpperLimit){ m_impulse.z = b2Math.b2Min(m_impulse.z, 0); }; }; bX = (-(Cdot1X) - ((m_impulse.z - f1.z) * m_K.col3.x)); bY = (-(Cdot1Y) - ((m_impulse.z - f1.z) * m_K.col3.y)); f2r = m_K.Solve22(new b2Vec2(), bX, bY); f2r.x = (f2r.x + f1.x); f2r.y = (f2r.y + f1.y); m_impulse.x = f2r.x; m_impulse.y = f2r.y; df.x = (m_impulse.x - f1.x); df.y = (m_impulse.y - f1.y); df.z = (m_impulse.z - f1.z); PX = ((df.x * m_perp.x) + (df.z * m_axis.x)); PY = ((df.x * m_perp.y) + (df.z * m_axis.y)); L1 = (((df.x * m_s1) + df.y) + (df.z * m_a1)); L2 = (((df.x * m_s2) + df.y) + (df.z * m_a2)); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); } else { df2 = m_K.Solve22(new b2Vec2(), -(Cdot1X), -(Cdot1Y)); m_impulse.x = (m_impulse.x + df2.x); m_impulse.y = (m_impulse.y + df2.y); PX = (df2.x * m_perp.x); PY = (df2.x * m_perp.y); L1 = ((df2.x * m_s1) + df2.y); L2 = ((df2.x * m_s2) + df2.y); v1.x = (v1.x - (m_invMass1 * PX)); v1.y = (v1.y - (m_invMass1 * PY)); w1 = (w1 - (m_invI1 * L1)); v2.x = (v2.x + (m_invMass2 * PX)); v2.y = (v2.y + (m_invMass2 * PY)); w2 = (w2 + (m_invI2 * L2)); }; b1.m_linearVelocity.SetV(v1); b1.m_angularVelocity = w1; b2.m_linearVelocity.SetV(v2); b2.m_angularVelocity = w2; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } public function GetUpperLimit():Number{ return (m_upperTranslation); } public function GetLowerLimit():Number{ return (m_lowerTranslation); } public function EnableMotor(flag:Boolean):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_enableMotor = flag; } public function GetJointTranslation():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var p1:b2Vec2 = b1.GetWorldPoint(m_localAnchor1); var p2:b2Vec2 = b2.GetWorldPoint(m_localAnchor2); var dX:Number = (p2.x - p1.x); var dY:Number = (p2.y - p1.y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var translation:Number = ((axis.x * dX) + (axis.y * dY)); return (translation); } public function GetMotorSpeed():Number{ return (m_motorSpeed); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2((inv_dt * ((m_impulse.x * m_perp.x) + ((m_motorImpulse + m_impulse.z) * m_axis.x))), (inv_dt * ((m_impulse.x * m_perp.y) + ((m_motorImpulse + m_impulse.z) * m_axis.y))))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var limitC:Number; var oldLimitImpulse:Number; var tMat:b2Mat22; var tX:Number; var m1:Number; var m2:Number; var i1:Number; var i2:Number; var translation:Number; var k11:Number; var k12:Number; var k22:Number; var impulse1:b2Vec2; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var c1:b2Vec2 = b1.m_sweep.c; var a1:Number = b1.m_sweep.a; var c2:b2Vec2 = b2.m_sweep.c; var a2:Number = b2.m_sweep.a; var linearError:Number = 0; var angularError:Number = 0; var active:Boolean; var C2:Number = 0; var R1:b2Mat22 = new b2Mat22(a1); var R2:b2Mat22 = new b2Mat22(a2); tMat = R1; var r1X:Number = (m_localAnchor1.x - m_localCenter1.x); var r1Y:Number = (m_localAnchor1.y - m_localCenter1.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = R2; var r2X:Number = (m_localAnchor2.x - m_localCenter2.x); var r2Y:Number = (m_localAnchor2.y - m_localCenter2.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((c2.x + r2X) - c1.x) - r1X); var dY:Number = (((c2.y + r2Y) - c1.y) - r1Y); if (m_enableLimit){ m_axis = b2Math.b2MulMV(R1, m_localXAxis1); m_a1 = (((dX + r1X) * m_axis.y) - ((dY + r1Y) * m_axis.x)); m_a2 = ((r2X * m_axis.y) - (r2Y * m_axis.x)); translation = ((m_axis.x * dX) + (m_axis.y * dY)); if (b2Math.b2Abs((m_upperTranslation - m_lowerTranslation)) < (2 * b2Settings.b2_linearSlop)){ C2 = b2Math.b2Clamp(translation, -(b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection); linearError = b2Math.b2Abs(translation); active = true; } else { if (translation <= m_lowerTranslation){ C2 = b2Math.b2Clamp(((translation - m_lowerTranslation) + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); linearError = (m_lowerTranslation - translation); active = true; } else { if (translation >= m_upperTranslation){ C2 = b2Math.b2Clamp(((translation - m_upperTranslation) + b2Settings.b2_linearSlop), 0, b2Settings.b2_maxLinearCorrection); linearError = (translation - m_upperTranslation); active = true; }; }; }; }; m_perp = b2Math.b2MulMV(R1, m_localYAxis1); m_s1 = (((dX + r1X) * m_perp.y) - ((dY + r1Y) * m_perp.x)); m_s2 = ((r2X * m_perp.y) - (r2Y * m_perp.x)); var impulse:b2Vec3 = new b2Vec3(); var C1X:Number = ((m_perp.x * dX) + (m_perp.y * dY)); var C1Y:Number = ((a2 - a1) - m_refAngle); linearError = b2Math.b2Max(linearError, b2Math.b2Abs(C1X)); angularError = b2Math.b2Abs(C1Y); if (active){ m1 = m_invMass1; m2 = m_invMass2; i1 = m_invI1; i2 = m_invI2; m_K.col1.x = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); m_K.col1.y = ((i1 * m_s1) + (i2 * m_s2)); m_K.col1.z = (((i1 * m_s1) * m_a1) + ((i2 * m_s2) * m_a2)); m_K.col2.x = m_K.col1.y; m_K.col2.y = (i1 + i2); m_K.col2.z = ((i1 * m_a1) + (i2 * m_a2)); m_K.col3.x = m_K.col1.z; m_K.col3.y = m_K.col2.z; m_K.col3.z = (((m1 + m2) + ((i1 * m_a1) * m_a1)) + ((i2 * m_a2) * m_a2)); m_K.Solve33(impulse, -(C1X), -(C1Y), -(C2)); } else { m1 = m_invMass1; m2 = m_invMass2; i1 = m_invI1; i2 = m_invI2; k11 = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); k12 = ((i1 * m_s1) + (i2 * m_s2)); k22 = (i1 + i2); m_K.col1.Set(k11, k12, 0); m_K.col2.Set(k12, k22, 0); impulse1 = m_K.Solve22(new b2Vec2(), -(C1X), -(C1Y)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; }; var PX:Number = ((impulse.x * m_perp.x) + (impulse.z * m_axis.x)); var PY:Number = ((impulse.x * m_perp.y) + (impulse.z * m_axis.y)); var L1:Number = (((impulse.x * m_s1) + impulse.y) + (impulse.z * m_a1)); var L2:Number = (((impulse.x * m_s2) + impulse.y) + (impulse.z * m_a2)); c1.x = (c1.x - (m_invMass1 * PX)); c1.y = (c1.y - (m_invMass1 * PY)); a1 = (a1 - (m_invI1 * L1)); c2.x = (c2.x + (m_invMass2 * PX)); c2.y = (c2.y + (m_invMass2 * PY)); a2 = (a2 + (m_invI2 * L2)); b1.m_sweep.a = a1; b2.m_sweep.a = a2; b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((((linearError <= b2Settings.b2_linearSlop)) && ((angularError <= b2Settings.b2_angularSlop)))); } public function SetMotorSpeed(speed:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_motorSpeed = speed; } public function GetJointSpeed():Number{ var tMat:b2Mat22; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var dX:Number = (p2X - p1X); var dY:Number = (p2Y - p1Y); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var v1:b2Vec2 = b1.m_linearVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var w2:Number = b2.m_angularVelocity; var speed:Number = (((dX * (-(w1) * axis.y)) + (dY * (w1 * axis.x))) + ((axis.x * (((v2.x + (-(w2) * r2Y)) - v1.x) - (-(w1) * r1Y))) + (axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X))))); return (speed); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var jointTransition:Number; var PX:Number; var PY:Number; var L1:Number; var L2:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; m_localCenter1.SetV(b1.GetLocalCenter()); m_localCenter2.SetV(b2.GetLocalCenter()); var xf1:b2XForm = b1.GetXForm(); var xf2:b2XForm = b2.GetXForm(); tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var dX:Number = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); var dY:Number = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); m_invMass1 = b1.m_invMass; m_invMass2 = b2.m_invMass; m_invI1 = b1.m_invI; m_invI2 = b2.m_invI; m_axis.SetV(b2Math.b2MulMV(xf1.R, m_localXAxis1)); m_a1 = (((dX + r1X) * m_axis.y) - ((dY + r1Y) * m_axis.x)); m_a2 = ((r2X * m_axis.y) - (r2Y * m_axis.x)); m_motorMass = (((m_invMass1 + m_invMass2) + ((m_invI1 * m_a1) * m_a1)) + ((m_invI2 * m_a2) * m_a2)); m_motorMass = (1 / m_motorMass); m_perp.SetV(b2Math.b2MulMV(xf1.R, m_localYAxis1)); m_s1 = (((dX + r1X) * m_perp.y) - ((dY + r1Y) * m_perp.x)); m_s2 = ((r2X * m_perp.y) - (r2Y * m_perp.x)); var m1:Number = m_invMass1; var m2:Number = m_invMass2; var i1:Number = m_invI1; var i2:Number = m_invI2; m_K.col1.x = (((m1 + m2) + ((i1 * m_s1) * m_s1)) + ((i2 * m_s2) * m_s2)); m_K.col1.y = ((i1 * m_s1) + (i2 * m_s2)); m_K.col1.z = (((i1 * m_s1) * m_a1) + ((i2 * m_s2) * m_a2)); m_K.col2.x = m_K.col1.y; m_K.col2.y = (i1 + i2); m_K.col2.z = ((i1 * m_a1) + (i2 * m_a2)); m_K.col3.x = m_K.col1.z; m_K.col3.y = m_K.col2.z; m_K.col3.z = (((m1 + m2) + ((i1 * m_a1) * m_a1)) + ((i2 * m_a2) * m_a2)); if (m_enableLimit){ jointTransition = ((m_axis.x * dX) + (m_axis.y * dY)); if (b2Math.b2Abs((m_upperTranslation - m_lowerTranslation)) < (2 * b2Settings.b2_linearSlop)){ m_limitState = e_equalLimits; } else { if (jointTransition <= m_lowerTranslation){ if (m_limitState != e_atLowerLimit){ m_limitState = e_atLowerLimit; m_impulse.z = 0; }; } else { if (jointTransition >= m_upperTranslation){ if (m_limitState != e_atUpperLimit){ m_limitState = e_atUpperLimit; m_impulse.z = 0; }; } else { m_limitState = e_inactiveLimit; m_impulse.z = 0; }; }; }; } else { m_limitState = e_inactiveLimit; }; if (m_enableMotor == false){ m_motorImpulse = 0; }; if (step.warmStarting){ m_impulse.x = (m_impulse.x * step.dtRatio); m_impulse.y = (m_impulse.y * step.dtRatio); m_motorImpulse = (m_motorImpulse * step.dtRatio); PX = ((m_impulse.x * m_perp.x) + ((m_motorImpulse + m_impulse.z) * m_axis.x)); PY = ((m_impulse.x * m_perp.y) + ((m_motorImpulse + m_impulse.z) * m_axis.y)); L1 = (((m_impulse.x * m_s1) + m_impulse.y) + ((m_motorImpulse + m_impulse.z) * m_a1)); L2 = (((m_impulse.x * m_s2) + m_impulse.y) + ((m_motorImpulse + m_impulse.z) * m_a2)); b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (m_invMass1 * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (m_invMass1 * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (m_invI1 * L1)); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (m_invMass2 * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (m_invMass2 * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (m_invI2 * L2)); } else { m_impulse.SetZero(); m_motorImpulse = 0; }; } public function GetMotorForce():Number{ return (m_motorImpulse); } public function EnableLimit(flag:Boolean):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_enableLimit = flag; } public function SetMaxMotorForce(force:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_maxMotorForce = force; } override public function GetReactionTorque(inv_dt:Number):Number{ return ((inv_dt * m_impulse.y)); } public function IsLimitEnabled():Boolean{ return (m_enableLimit); } public function IsMotorEnabled():Boolean{ return (m_enableMotor); } public function SetLimits(lower:Number, upper:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_lowerTranslation = lower; m_upperTranslation = upper; } } }//package Box2D.Dynamics.Joints
Section 69
//b2PrismaticJointDef (Box2D.Dynamics.Joints.b2PrismaticJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class b2PrismaticJointDef extends b2JointDef { public var motorSpeed:Number; public var localAxis1:b2Vec2; public var referenceAngle:Number; public var upperTranslation:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var enableLimit:Boolean; public var enableMotor:Boolean; public var maxMotorForce:Number; public var lowerTranslation:Number; public function b2PrismaticJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); localAxis1 = new b2Vec2(); super(); type = b2Joint.e_prismaticJoint; localAxis1.Set(1, 0); referenceAngle = 0; enableLimit = false; lowerTranslation = 0; upperTranslation = 0; enableMotor = false; maxMotorForce = 0; motorSpeed = 0; } public function Initialize(b1:b2Body, b2:b2Body, anchor:b2Vec2, axis:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1 = body1.GetLocalPoint(anchor); localAnchor2 = body2.GetLocalPoint(anchor); localAxis1 = body1.GetLocalVector(axis); referenceAngle = (body2.GetAngle() - body1.GetAngle()); } } }//package Box2D.Dynamics.Joints
Section 70
//b2PulleyJoint (Box2D.Dynamics.Joints.b2PulleyJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2PulleyJoint extends b2Joint { private var m_limitState1:int; private var m_limitState2:int; private var m_ground:b2Body; private var m_maxLength2:Number; private var m_maxLength1:Number; private var m_impulse:Number; private var m_constant:Number; private var m_state:int; private var m_ratio:Number; private var m_groundAnchor1:b2Vec2; private var m_groundAnchor2:b2Vec2; private var m_localAnchor1:b2Vec2; private var m_localAnchor2:b2Vec2; private var m_limitMass1:Number; private var m_limitMass2:Number; private var m_pulleyMass:Number; private var m_limitImpulse1:Number; private var m_limitImpulse2:Number; private var m_u1:b2Vec2; private var m_u2:b2Vec2; b2internal static const b2_minPulleyLength:Number = 2; public function b2PulleyJoint(def:b2PulleyJointDef){ var tMat:b2Mat22; var tX:Number; var tY:Number; m_groundAnchor1 = new b2Vec2(); m_groundAnchor2 = new b2Vec2(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_u1 = new b2Vec2(); m_u2 = new b2Vec2(); super(def); m_ground = m_body1.m_world.m_groundBody; m_groundAnchor1.x = (def.groundAnchor1.x - m_ground.m_xf.position.x); m_groundAnchor1.y = (def.groundAnchor1.y - m_ground.m_xf.position.y); m_groundAnchor2.x = (def.groundAnchor2.x - m_ground.m_xf.position.x); m_groundAnchor2.y = (def.groundAnchor2.y - m_ground.m_xf.position.y); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_ratio = def.ratio; m_constant = (def.length1 + (m_ratio * def.length2)); m_maxLength1 = b2Math.b2Min(def.maxLength1, (m_constant - (m_ratio * b2_minPulleyLength))); m_maxLength2 = b2Math.b2Min(def.maxLength2, ((m_constant - b2_minPulleyLength) / m_ratio)); m_impulse = 0; m_limitImpulse1 = 0; m_limitImpulse2 = 0; } public function GetGroundAnchor2():b2Vec2{ var a:b2Vec2 = m_ground.m_xf.position.Copy(); a.Add(m_groundAnchor2); return (a); } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2(((inv_dt * m_impulse) * m_u2.x), ((inv_dt * m_impulse) * m_u2.y))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var tMat:b2Mat22; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var p1X:Number; var p1Y:Number; var p2X:Number; var p2Y:Number; var length1:Number; var length2:Number; var C:Number; var impulse:Number; var oldImpulse:Number; var oldLimitPositionImpulse:Number; var tX:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var s1X:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var s1Y:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var s2X:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var s2Y:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); var linearError:Number = 0; if (m_state == e_atUpperLimit){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p1X = (b1.m_sweep.c.x + r1X); p1Y = (b1.m_sweep.c.y + r1Y); p2X = (b2.m_sweep.c.x + r2X); p2Y = (b2.m_sweep.c.y + r2Y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); m_u2.Set((p2X - s2X), (p2Y - s2Y)); length1 = m_u1.Length(); length2 = m_u2.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.Multiply((1 / length1)); } else { m_u1.SetZero(); }; if (length2 > b2Settings.b2_linearSlop){ m_u2.Multiply((1 / length2)); } else { m_u2.SetZero(); }; C = ((m_constant - length1) - (m_ratio * length2)); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_pulleyMass) * C); p1X = (-(impulse) * m_u1.x); p1Y = (-(impulse) * m_u1.y); p2X = ((-(m_ratio) * impulse) * m_u2.x); p2Y = ((-(m_ratio) * impulse) * m_u2.y); b1.m_sweep.c.x = (b1.m_sweep.c.x + (b1.m_invMass * p1X)); b1.m_sweep.c.y = (b1.m_sweep.c.y + (b1.m_invMass * p1Y)); b1.m_sweep.a = (b1.m_sweep.a + (b1.m_invI * ((r1X * p1Y) - (r1Y * p1X)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * p2X)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * p2Y)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * p2Y) - (r2Y * p2X)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); }; if (m_limitState1 == e_atUpperLimit){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; p1X = (b1.m_sweep.c.x + r1X); p1Y = (b1.m_sweep.c.y + r1Y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); length1 = m_u1.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.x = (m_u1.x * (1 / length1)); m_u1.y = (m_u1.y * (1 / length1)); } else { m_u1.SetZero(); }; C = (m_maxLength1 - length1); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_limitMass1) * C); p1X = (-(impulse) * m_u1.x); p1Y = (-(impulse) * m_u1.y); b1.m_sweep.c.x = (b1.m_sweep.c.x + (b1.m_invMass * p1X)); b1.m_sweep.c.y = (b1.m_sweep.c.y + (b1.m_invMass * p1Y)); b1.m_sweep.a = (b1.m_sweep.a + (b1.m_invI * ((r1X * p1Y) - (r1Y * p1X)))); b1.SynchronizeTransform(); }; if (m_limitState2 == e_atUpperLimit){ tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; p2X = (b2.m_sweep.c.x + r2X); p2Y = (b2.m_sweep.c.y + r2Y); m_u2.Set((p2X - s2X), (p2Y - s2Y)); length2 = m_u2.Length(); if (length2 > b2Settings.b2_linearSlop){ m_u2.x = (m_u2.x * (1 / length2)); m_u2.y = (m_u2.y * (1 / length2)); } else { m_u2.SetZero(); }; C = (m_maxLength2 - length2); linearError = b2Math.b2Max(linearError, -(C)); C = b2Math.b2Clamp((C + b2Settings.b2_linearSlop), -(b2Settings.b2_maxLinearCorrection), 0); impulse = (-(m_limitMass2) * C); p2X = (-(impulse) * m_u2.x); p2Y = (-(impulse) * m_u2.y); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * p2X)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * p2Y)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * p2Y) - (r2Y * p2X)))); b2.SynchronizeTransform(); }; return ((linearError < b2Settings.b2_linearSlop)); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var b1:b2Body; var tMat:b2Mat22; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; b1 = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var p1X:Number = (b1.m_sweep.c.x + r1X); var p1Y:Number = (b1.m_sweep.c.y + r1Y); var p2X:Number = (b2.m_sweep.c.x + r2X); var p2Y:Number = (b2.m_sweep.c.y + r2Y); var s1X:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var s1Y:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var s2X:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var s2Y:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); m_u1.Set((p1X - s1X), (p1Y - s1Y)); m_u2.Set((p2X - s2X), (p2Y - s2Y)); var length1:Number = m_u1.Length(); var length2:Number = m_u2.Length(); if (length1 > b2Settings.b2_linearSlop){ m_u1.Multiply((1 / length1)); } else { m_u1.SetZero(); }; if (length2 > b2Settings.b2_linearSlop){ m_u2.Multiply((1 / length2)); } else { m_u2.SetZero(); }; var C:Number = ((m_constant - length1) - (m_ratio * length2)); if (C > 0){ m_state = e_inactiveLimit; m_impulse = 0; } else { m_state = e_atUpperLimit; }; if (length1 < m_maxLength1){ m_limitState1 = e_inactiveLimit; m_limitImpulse1 = 0; } else { m_limitState1 = e_atUpperLimit; }; if (length2 < m_maxLength2){ m_limitState2 = e_inactiveLimit; m_limitImpulse2 = 0; } else { m_limitState2 = e_atUpperLimit; }; var cr1u1:Number = ((r1X * m_u1.y) - (r1Y * m_u1.x)); var cr2u2:Number = ((r2X * m_u2.y) - (r2Y * m_u2.x)); m_limitMass1 = (b1.m_invMass + ((b1.m_invI * cr1u1) * cr1u1)); m_limitMass2 = (b2.m_invMass + ((b2.m_invI * cr2u2) * cr2u2)); m_pulleyMass = (m_limitMass1 + ((m_ratio * m_ratio) * m_limitMass2)); m_limitMass1 = (1 / m_limitMass1); m_limitMass2 = (1 / m_limitMass2); m_pulleyMass = (1 / m_pulleyMass); if (step.warmStarting){ m_impulse = (m_impulse * step.dtRatio); m_limitImpulse1 = (m_limitImpulse1 * step.dtRatio); m_limitImpulse2 = (m_limitImpulse2 * step.dtRatio); P1X = ((-(m_impulse) - m_limitImpulse1) * m_u1.x); P1Y = ((-(m_impulse) - m_limitImpulse1) * m_u1.y); P2X = (((-(m_ratio) * m_impulse) - m_limitImpulse2) * m_u2.x); P2Y = (((-(m_ratio) * m_impulse) - m_limitImpulse2) * m_u2.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); } else { m_impulse = 0; m_limitImpulse1 = 0; m_limitImpulse2 = 0; }; } override public function GetReactionTorque(inv_dt:Number):Number{ return (0); } public function GetRatio():Number{ return (m_ratio); } public function GetLength2():Number{ var p:b2Vec2 = m_body2.GetWorldPoint(m_localAnchor2); var sX:Number = (m_ground.m_xf.position.x + m_groundAnchor2.x); var sY:Number = (m_ground.m_xf.position.y + m_groundAnchor2.y); var dX:Number = (p.x - sX); var dY:Number = (p.y - sY); return (Math.sqrt(((dX * dX) + (dY * dY)))); } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var v1X:Number; var v1Y:Number; var v2X:Number; var v2Y:Number; var P1X:Number; var P1Y:Number; var P2X:Number; var P2Y:Number; var Cdot:Number; var impulse:Number; var oldImpulse:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); var tX:Number = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; if (m_state == e_atUpperLimit){ v1X = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); v1Y = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); v2X = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); v2Y = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); Cdot = (-(((m_u1.x * v1X) + (m_u1.y * v1Y))) - (m_ratio * ((m_u2.x * v2X) + (m_u2.y * v2Y)))); impulse = (m_pulleyMass * -(Cdot)); oldImpulse = m_impulse; m_impulse = b2Math.b2Max(0, (m_impulse + impulse)); impulse = (m_impulse - oldImpulse); P1X = (-(impulse) * m_u1.x); P1Y = (-(impulse) * m_u1.y); P2X = ((-(m_ratio) * impulse) * m_u2.x); P2Y = ((-(m_ratio) * impulse) * m_u2.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); }; if (m_limitState1 == e_atUpperLimit){ v1X = (b1.m_linearVelocity.x + (-(b1.m_angularVelocity) * r1Y)); v1Y = (b1.m_linearVelocity.y + (b1.m_angularVelocity * r1X)); Cdot = -(((m_u1.x * v1X) + (m_u1.y * v1Y))); impulse = (-(m_limitMass1) * Cdot); oldImpulse = m_limitImpulse1; m_limitImpulse1 = b2Math.b2Max(0, (m_limitImpulse1 + impulse)); impulse = (m_limitImpulse1 - oldImpulse); P1X = (-(impulse) * m_u1.x); P1Y = (-(impulse) * m_u1.y); b1.m_linearVelocity.x = (b1.m_linearVelocity.x + (b1.m_invMass * P1X)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y + (b1.m_invMass * P1Y)); b1.m_angularVelocity = (b1.m_angularVelocity + (b1.m_invI * ((r1X * P1Y) - (r1Y * P1X)))); }; if (m_limitState2 == e_atUpperLimit){ v2X = (b2.m_linearVelocity.x + (-(b2.m_angularVelocity) * r2Y)); v2Y = (b2.m_linearVelocity.y + (b2.m_angularVelocity * r2X)); Cdot = -(((m_u2.x * v2X) + (m_u2.y * v2Y))); impulse = (-(m_limitMass2) * Cdot); oldImpulse = m_limitImpulse2; m_limitImpulse2 = b2Math.b2Max(0, (m_limitImpulse2 + impulse)); impulse = (m_limitImpulse2 - oldImpulse); P2X = (-(impulse) * m_u2.x); P2Y = (-(impulse) * m_u2.y); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (b2.m_invMass * P2X)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (b2.m_invMass * P2Y)); b2.m_angularVelocity = (b2.m_angularVelocity + (b2.m_invI * ((r2X * P2Y) - (r2Y * P2X)))); }; } public function GetLength1():Number{ var p:b2Vec2 = m_body1.GetWorldPoint(m_localAnchor1); var sX:Number = (m_ground.m_xf.position.x + m_groundAnchor1.x); var sY:Number = (m_ground.m_xf.position.y + m_groundAnchor1.y); var dX:Number = (p.x - sX); var dY:Number = (p.y - sY); return (Math.sqrt(((dX * dX) + (dY * dY)))); } public function GetGroundAnchor1():b2Vec2{ var a:b2Vec2 = m_ground.m_xf.position.Copy(); a.Add(m_groundAnchor1); return (a); } } }//package Box2D.Dynamics.Joints
Section 71
//b2PulleyJointDef (Box2D.Dynamics.Joints.b2PulleyJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class b2PulleyJointDef extends b2JointDef { public var maxLength1:Number; public var maxLength2:Number; public var length1:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var groundAnchor1:b2Vec2; public var groundAnchor2:b2Vec2; public var ratio:Number; public var length2:Number; public function b2PulleyJointDef(){ groundAnchor1 = new b2Vec2(); groundAnchor2 = new b2Vec2(); localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_pulleyJoint; groundAnchor1.Set(-1, 1); groundAnchor2.Set(1, 1); localAnchor1.Set(-1, 0); localAnchor2.Set(1, 0); length1 = 0; maxLength1 = 0; length2 = 0; maxLength2 = 0; ratio = 1; collideConnected = true; } public function Initialize(b1:b2Body, b2:b2Body, ga1:b2Vec2, ga2:b2Vec2, anchor1:b2Vec2, anchor2:b2Vec2, r:Number):void{ body1 = b1; body2 = b2; groundAnchor1.SetV(ga1); groundAnchor2.SetV(ga2); localAnchor1 = body1.GetLocalPoint(anchor1); localAnchor2 = body2.GetLocalPoint(anchor2); var d1X:Number = (anchor1.x - ga1.x); var d1Y:Number = (anchor1.y - ga1.y); length1 = Math.sqrt(((d1X * d1X) + (d1Y * d1Y))); var d2X:Number = (anchor2.x - ga2.x); var d2Y:Number = (anchor2.y - ga2.y); length2 = Math.sqrt(((d2X * d2X) + (d2Y * d2Y))); ratio = r; var C:Number = (length1 + (ratio * length2)); maxLength1 = (C - (ratio * b2PulleyJoint.b2_minPulleyLength)); maxLength2 = ((C - b2PulleyJoint.b2_minPulleyLength) / ratio); } } }//package Box2D.Dynamics.Joints
Section 72
//b2RevoluteJoint (Box2D.Dynamics.Joints.b2RevoluteJoint) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Common.*; public class b2RevoluteJoint extends b2Joint { private var m_mass:b2Mat33; private var m_impulse:b2Vec3; private var m_enableLimit:Boolean; private var m_limitState:int; private var m_motorMass:Number; b2internal var m_localAnchor1:b2Vec2; b2internal var m_localAnchor2:b2Vec2; private var K1:b2Mat22; private var K2:b2Mat22; private var K3:b2Mat22; private var K:b2Mat22; private var m_motorImpulse:Number; private var m_enableMotor:Boolean; private var m_referenceAngle:Number; private var m_upperAngle:Number; private var m_motorSpeed:Number; private var m_lowerAngle:Number; private var m_maxMotorTorque:Number; private static var tImpulse:b2Vec2 = new b2Vec2(); public function b2RevoluteJoint(def:b2RevoluteJointDef){ K = new b2Mat22(); K1 = new b2Mat22(); K2 = new b2Mat22(); K3 = new b2Mat22(); m_localAnchor1 = new b2Vec2(); m_localAnchor2 = new b2Vec2(); m_impulse = new b2Vec3(); m_mass = new b2Mat33(); super(def); m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_referenceAngle = def.referenceAngle; m_impulse.SetZero(); m_motorImpulse = 0; m_lowerAngle = def.lowerAngle; m_upperAngle = def.upperAngle; m_maxMotorTorque = def.maxMotorTorque; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; m_limitState = e_inactiveLimit; } override b2internal function SolveVelocityConstraints(step:b2TimeStep):void{ var tMat:b2Mat22; var tX:Number; var newImpulse:Number; var reduced:b2Vec2; var r1X:Number; var r1Y:Number; var r2X:Number; var r2Y:Number; var Cdot:Number; var impulse:Number; var oldImpulse:Number; var maxImpulse:Number; var Cdot1X:Number; var Cdot1Y:Number; var Cdot2:Number; var impulse3:b2Vec3; var CdotX:Number; var CdotY:Number; var impulse2:b2Vec2; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var v1:b2Vec2 = b1.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w2:Number = b2.m_angularVelocity; var m1:Number = b1.m_invMass; var m2:Number = b2.m_invMass; var i1:Number = b1.m_invI; var i2:Number = b2.m_invI; if (((m_enableMotor) && (!((m_limitState == e_equalLimits))))){ Cdot = ((w2 - w1) - m_motorSpeed); impulse = (m_motorMass * -(Cdot)); oldImpulse = m_motorImpulse; maxImpulse = (step.dt * m_maxMotorTorque); m_motorImpulse = b2Math.b2Clamp((m_motorImpulse + impulse), -(maxImpulse), maxImpulse); impulse = (m_motorImpulse - oldImpulse); w1 = (w1 - (i1 * impulse)); w2 = (w2 + (i2 * impulse)); }; if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; Cdot1X = (((v2.x + (-(w2) * r2Y)) - v1.x) - (-(w1) * r1Y)); Cdot1Y = (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)); Cdot2 = (w2 - w1); impulse3 = m_mass.Solve33(new b2Vec3(), -(Cdot1X), -(Cdot1Y), -(Cdot2)); if (m_limitState == e_equalLimits){ m_impulse.Add(impulse3); } else { if (m_limitState == e_atLowerLimit){ newImpulse = (m_impulse.z + impulse3.z); if (newImpulse < 0){ reduced = m_mass.Solve22(new b2Vec2(), -(Cdot1X), -(Cdot1Y)); impulse3.x = reduced.x; impulse3.y = reduced.y; impulse3.z = -(m_impulse.z); m_impulse.x = (m_impulse.x + reduced.x); m_impulse.y = (m_impulse.y + reduced.y); m_impulse.z = 0; }; } else { if (m_limitState == e_atUpperLimit){ newImpulse = (m_impulse.z + impulse3.z); if (newImpulse > 0){ reduced = m_mass.Solve22(new b2Vec2(), -(Cdot1X), -(Cdot1Y)); impulse3.x = reduced.x; impulse3.y = reduced.y; impulse3.z = -(m_impulse.z); m_impulse.x = (m_impulse.x + reduced.x); m_impulse.y = (m_impulse.y + reduced.y); m_impulse.z = 0; }; }; }; }; v1.x = (v1.x - (m1 * impulse3.x)); v1.y = (v1.y - (m1 * impulse3.y)); w1 = (w1 - (i1 * (((r1X * impulse3.y) - (r1Y * impulse3.x)) + impulse3.z))); v2.x = (v2.x + (m2 * impulse3.x)); v2.y = (v2.y + (m2 * impulse3.y)); w2 = (w2 + (i2 * (((r2X * impulse3.y) - (r2Y * impulse3.x)) + impulse3.z))); } else { tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; r2X = (m_localAnchor2.x - b2.m_sweep.localCenter.x); r2Y = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; CdotX = (((v2.x + (-(w2) * r2Y)) - v1.x) - (-(w1) * r1Y)); CdotY = (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)); impulse2 = m_mass.Solve22(new b2Vec2(), -(CdotX), -(CdotY)); m_impulse.x = (m_impulse.x + impulse2.x); m_impulse.y = (m_impulse.y + impulse2.y); v1.x = (v1.x - (m1 * impulse2.x)); v1.y = (v1.y - (m1 * impulse2.y)); w1 = (w1 - (i1 * ((r1X * impulse2.y) - (r1Y * impulse2.x)))); v2.x = (v2.x + (m2 * impulse2.x)); v2.y = (v2.y + (m2 * impulse2.y)); w2 = (w2 + (i2 * ((r2X * impulse2.y) - (r2Y * impulse2.x)))); }; b1.m_linearVelocity.SetV(v1); b1.m_angularVelocity = w1; b2.m_linearVelocity.SetV(v2); b2.m_angularVelocity = w2; } override public function GetAnchor1():b2Vec2{ return (m_body1.GetWorldPoint(m_localAnchor1)); } override public function GetAnchor2():b2Vec2{ return (m_body2.GetWorldPoint(m_localAnchor2)); } public function GetUpperLimit():Number{ return (m_upperAngle); } public function GetLowerLimit():Number{ return (m_lowerAngle); } public function EnableMotor(flag:Boolean):void{ m_enableMotor = flag; } public function GetMotorSpeed():Number{ return (m_motorSpeed); } override public function GetReactionForce(inv_dt:Number):b2Vec2{ return (new b2Vec2((inv_dt * m_impulse.x), (inv_dt * m_impulse.y))); } override b2internal function SolvePositionConstraints(baumgarte:Number):Boolean{ var oldLimitImpulse:Number; var C:Number; var tMat:b2Mat22; var tX:Number; var impulseX:Number; var impulseY:Number; var angle:Number; var limitImpulse:Number; var uX:Number; var uY:Number; var k:Number; var m:Number; var k_beta:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var angularError:Number = 0; var positionError:Number = 0; if (((m_enableLimit) && (!((m_limitState == e_inactiveLimit))))){ angle = ((b2.m_sweep.a - b1.m_sweep.a) - m_referenceAngle); limitImpulse = 0; if (m_limitState == e_equalLimits){ C = b2Math.b2Clamp(angle, -(b2Settings.b2_maxAngularCorrection), b2Settings.b2_maxAngularCorrection); limitImpulse = (-(m_motorMass) * C); angularError = b2Math.b2Abs(C); } else { if (m_limitState == e_atLowerLimit){ C = (angle - m_lowerAngle); angularError = -(C); C = b2Math.b2Clamp((C + b2Settings.b2_angularSlop), -(b2Settings.b2_maxAngularCorrection), 0); limitImpulse = (-(m_motorMass) * C); } else { if (m_limitState == e_atUpperLimit){ C = (angle - m_upperAngle); angularError = C; C = b2Math.b2Clamp((C - b2Settings.b2_angularSlop), 0, b2Settings.b2_maxAngularCorrection); limitImpulse = (-(m_motorMass) * C); }; }; }; b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * limitImpulse)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * limitImpulse)); b1.SynchronizeTransform(); b2.SynchronizeTransform(); }; tMat = b1.m_xf.R; var r1X:Number = (m_localAnchor1.x - b1.m_sweep.localCenter.x); var r1Y:Number = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var CX:Number = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); var CY:Number = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); var CLengthSquared:Number = ((CX * CX) + (CY * CY)); var CLength:Number = Math.sqrt(CLengthSquared); positionError = CLength; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; var k_allowedStretch:Number = (10 * b2Settings.b2_linearSlop); if (CLengthSquared > (k_allowedStretch * k_allowedStretch)){ uX = (CX / CLength); uY = (CY / CLength); k = (invMass1 + invMass2); m = (1 / k); impulseX = (m * -(CX)); impulseY = (m * -(CY)); k_beta = 0.5; b1.m_sweep.c.x = (b1.m_sweep.c.x - ((k_beta * invMass1) * impulseX)); b1.m_sweep.c.y = (b1.m_sweep.c.y - ((k_beta * invMass1) * impulseY)); b2.m_sweep.c.x = (b2.m_sweep.c.x + ((k_beta * invMass2) * impulseX)); b2.m_sweep.c.y = (b2.m_sweep.c.y + ((k_beta * invMass2) * impulseY)); CX = (((b2.m_sweep.c.x + r2X) - b1.m_sweep.c.x) - r1X); CY = (((b2.m_sweep.c.y + r2Y) - b1.m_sweep.c.y) - r1Y); }; K1.col1.x = (invMass1 + invMass2); K1.col2.x = 0; K1.col1.y = 0; K1.col2.y = (invMass1 + invMass2); K2.col1.x = ((invI1 * r1Y) * r1Y); K2.col2.x = ((-(invI1) * r1X) * r1Y); K2.col1.y = ((-(invI1) * r1X) * r1Y); K2.col2.y = ((invI1 * r1X) * r1X); K3.col1.x = ((invI2 * r2Y) * r2Y); K3.col2.x = ((-(invI2) * r2X) * r2Y); K3.col1.y = ((-(invI2) * r2X) * r2Y); K3.col2.y = ((invI2 * r2X) * r2X); K.SetM(K1); K.AddM(K2); K.AddM(K3); K.Solve(tImpulse, -(CX), -(CY)); impulseX = tImpulse.x; impulseY = tImpulse.y; b1.m_sweep.c.x = (b1.m_sweep.c.x - (b1.m_invMass * impulseX)); b1.m_sweep.c.y = (b1.m_sweep.c.y - (b1.m_invMass * impulseY)); b1.m_sweep.a = (b1.m_sweep.a - (b1.m_invI * ((r1X * impulseY) - (r1Y * impulseX)))); b2.m_sweep.c.x = (b2.m_sweep.c.x + (b2.m_invMass * impulseX)); b2.m_sweep.c.y = (b2.m_sweep.c.y + (b2.m_invMass * impulseY)); b2.m_sweep.a = (b2.m_sweep.a + (b2.m_invI * ((r2X * impulseY) - (r2Y * impulseX)))); b1.SynchronizeTransform(); b2.SynchronizeTransform(); return ((((positionError <= b2Settings.b2_linearSlop)) && ((angularError <= b2Settings.b2_angularSlop)))); } public function SetMotorSpeed(speed:Number):void{ m_body1.WakeUp(); m_body2.WakeUp(); m_motorSpeed = speed; } public function GetJointSpeed():Number{ return ((m_body2.m_angularVelocity - m_body1.m_angularVelocity)); } public function SetMaxMotorTorque(torque:Number):void{ m_maxMotorTorque = torque; } public function GetJointAngle():Number{ return (((m_body2.m_sweep.a - m_body1.m_sweep.a) - m_referenceAngle)); } public function GetMotorTorque():Number{ return (m_maxMotorTorque); } override b2internal function InitVelocityConstraints(step:b2TimeStep):void{ var b1:b2Body; var b2:b2Body; var tMat:b2Mat22; var tX:Number; var r1X:Number; var r1Y:Number; var jointAngle:Number; var PX:Number; var PY:Number; b1 = m_body1; b2 = m_body2; if (((m_enableMotor) || (m_enableLimit))){ }; tMat = b1.m_xf.R; r1X = (m_localAnchor1.x - b1.m_sweep.localCenter.x); r1Y = (m_localAnchor1.y - b1.m_sweep.localCenter.y); tX = ((tMat.col1.x * r1X) + (tMat.col2.x * r1Y)); r1Y = ((tMat.col1.y * r1X) + (tMat.col2.y * r1Y)); r1X = tX; tMat = b2.m_xf.R; var r2X:Number = (m_localAnchor2.x - b2.m_sweep.localCenter.x); var r2Y:Number = (m_localAnchor2.y - b2.m_sweep.localCenter.y); tX = ((tMat.col1.x * r2X) + (tMat.col2.x * r2Y)); r2Y = ((tMat.col1.y * r2X) + (tMat.col2.y * r2Y)); r2X = tX; var m1:Number = b1.m_invMass; var m2:Number = b2.m_invMass; var i1:Number = b1.m_invI; var i2:Number = b2.m_invI; m_mass.col1.x = (((m1 + m2) + ((r1Y * r1Y) * i1)) + ((r2Y * r2Y) * i2)); m_mass.col2.x = (((-(r1Y) * r1X) * i1) - ((r2Y * r2X) * i2)); m_mass.col3.x = ((-(r1Y) * i1) - (r2Y * i2)); m_mass.col1.y = m_mass.col2.x; m_mass.col2.y = (((m1 + m2) + ((r1X * r1X) * i1)) + ((r2X * r2X) * i2)); m_mass.col3.y = ((r1X * i1) + (r2X * i2)); m_mass.col1.z = m_mass.col3.x; m_mass.col2.z = m_mass.col3.y; m_mass.col3.z = (i1 + i2); m_motorMass = (1 / (i1 + i2)); if (m_enableMotor == false){ m_motorImpulse = 0; }; if (m_enableLimit){ jointAngle = ((b2.m_sweep.a - b1.m_sweep.a) - m_referenceAngle); if (b2Math.b2Abs((m_upperAngle - m_lowerAngle)) < (2 * b2Settings.b2_angularSlop)){ m_limitState = e_equalLimits; } else { if (jointAngle <= m_lowerAngle){ if (m_limitState != e_atLowerLimit){ m_impulse.z = 0; }; m_limitState = e_atLowerLimit; } else { if (jointAngle >= m_upperAngle){ if (m_limitState != e_atUpperLimit){ m_impulse.z = 0; }; m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_impulse.z = 0; }; }; }; } else { m_limitState = e_inactiveLimit; }; if (step.warmStarting){ m_impulse.x = (m_impulse.x * step.dtRatio); m_impulse.y = (m_impulse.y * step.dtRatio); m_motorImpulse = (m_motorImpulse * step.dtRatio); PX = m_impulse.x; PY = m_impulse.y; b1.m_linearVelocity.x = (b1.m_linearVelocity.x - (m1 * PX)); b1.m_linearVelocity.y = (b1.m_linearVelocity.y - (m1 * PY)); b1.m_angularVelocity = (b1.m_angularVelocity - (i1 * ((((r1X * PY) - (r1Y * PX)) + m_motorImpulse) + m_impulse.z))); b2.m_linearVelocity.x = (b2.m_linearVelocity.x + (m2 * PX)); b2.m_linearVelocity.y = (b2.m_linearVelocity.y + (m2 * PY)); b2.m_angularVelocity = (b2.m_angularVelocity + (i2 * ((((r2X * PY) - (r2Y * PX)) + m_motorImpulse) + m_impulse.z))); } else { m_impulse.SetZero(); m_motorImpulse = 0; }; } public function EnableLimit(flag:Boolean):void{ m_enableLimit = flag; } override public function GetReactionTorque(inv_dt:Number):Number{ return ((inv_dt * m_impulse.z)); } public function IsLimitEnabled():Boolean{ return (m_enableLimit); } public function IsMotorEnabled():Boolean{ m_body1.WakeUp(); m_body2.WakeUp(); return (m_enableMotor); } public function SetLimits(lower:Number, upper:Number):void{ m_lowerAngle = lower; m_upperAngle = upper; } } }//package Box2D.Dynamics.Joints
Section 73
//b2RevoluteJointDef (Box2D.Dynamics.Joints.b2RevoluteJointDef) package Box2D.Dynamics.Joints { import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class b2RevoluteJointDef extends b2JointDef { public var upperAngle:Number; public var enableMotor:Boolean; public var referenceAngle:Number; public var motorSpeed:Number; public var localAnchor1:b2Vec2; public var localAnchor2:b2Vec2; public var enableLimit:Boolean; public var lowerAngle:Number; public var maxMotorTorque:Number; public function b2RevoluteJointDef(){ localAnchor1 = new b2Vec2(); localAnchor2 = new b2Vec2(); super(); type = b2Joint.e_revoluteJoint; localAnchor1.Set(0, 0); localAnchor2.Set(0, 0); referenceAngle = 0; lowerAngle = 0; upperAngle = 0; maxMotorTorque = 0; motorSpeed = 0; enableLimit = false; enableMotor = false; } public function Initialize(b1:b2Body, b2:b2Body, anchor:b2Vec2):void{ body1 = b1; body2 = b2; localAnchor1 = body1.GetLocalPoint(anchor); localAnchor2 = body2.GetLocalPoint(anchor); referenceAngle = (body2.GetAngle() - body1.GetAngle()); } } }//package Box2D.Dynamics.Joints
Section 74
//b2Body (Box2D.Dynamics.b2Body) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Joints.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Controllers.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2Body { b2internal var m_xf:b2XForm; b2internal var m_controllerCount:int; b2internal var m_contactList:b2ContactEdge; b2internal var m_angularVelocity:Number; b2internal var m_invI:Number; b2internal var m_shapeCount:int; b2internal var m_torque:Number; b2internal var m_flags:uint; b2internal var m_linearVelocity:b2Vec2; b2internal var m_world:b2World; b2internal var m_controllerList:b2ControllerEdge; b2internal var m_next:b2Body; b2internal var m_mass:Number; b2internal var m_shapeList:b2Shape; b2internal var m_force:b2Vec2; b2internal var m_sweep:b2Sweep; private var m_userData; b2internal var m_invMass:Number; b2internal var m_prev:b2Body; b2internal var m_linearDamping:Number; private var m_type:int; b2internal var m_angularDamping:Number; b2internal var m_islandIndex:int; b2internal var m_sleepTime:Number; b2internal var m_jointList:b2JointEdge; b2internal var m_I:Number; b2internal static var e_fixedRotationFlag:uint = 64; b2internal static var e_frozenFlag:uint = 2; b2internal static var e_maxTypes:uint = 3; b2internal static var e_sleepFlag:uint = 8; private static var s_massData:b2MassData = new b2MassData(); b2internal static var e_bulletFlag:uint = 32; b2internal static var e_staticType:uint = 1; b2internal static var e_islandFlag:uint = 4; b2internal static var e_allowSleepFlag:uint = 16; private static var s_xf1:b2XForm = new b2XForm(); b2internal static var e_dynamicType:uint = 2; public function b2Body(bd:b2BodyDef, world:b2World){ m_xf = new b2XForm(); m_sweep = new b2Sweep(); m_linearVelocity = new b2Vec2(); m_force = new b2Vec2(); super(); m_flags = 0; if (bd.isBullet){ m_flags = (m_flags | e_bulletFlag); }; if (bd.fixedRotation){ m_flags = (m_flags | e_fixedRotationFlag); }; if (bd.allowSleep){ m_flags = (m_flags | e_allowSleepFlag); }; if (bd.isSleeping){ m_flags = (m_flags | e_sleepFlag); }; m_world = world; m_xf.position.SetV(bd.position); m_xf.R.Set(bd.angle); m_sweep.localCenter.SetV(bd.massData.center); m_sweep.t0 = 1; m_sweep.a0 = (m_sweep.a = bd.angle); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); m_jointList = null; m_controllerList = null; m_contactList = null; m_controllerCount = 0; m_prev = null; m_next = null; m_linearDamping = bd.linearDamping; m_angularDamping = bd.angularDamping; m_force.Set(0, 0); m_torque = 0; m_linearVelocity.SetZero(); m_angularVelocity = 0; m_sleepTime = 0; m_invMass = 0; m_I = 0; m_invI = 0; m_mass = bd.massData.mass; if (m_mass > 0){ m_invMass = (1 / m_mass); }; if ((m_flags & b2Body.e_fixedRotationFlag) == 0){ m_I = bd.massData.I; }; if (m_I > 0){ m_invI = (1 / m_I); }; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; m_userData = bd.userData; m_shapeList = null; m_shapeCount = 0; } public function SetLinearVelocity(v:b2Vec2):void{ m_linearVelocity.SetV(v); } public function IsSleeping():Boolean{ return (((m_flags & e_sleepFlag) == e_sleepFlag)); } b2internal function SynchronizeTransform():void{ m_xf.R.Set(m_sweep.a); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_xf.position.x = (m_sweep.c.x - ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); m_xf.position.y = (m_sweep.c.y - ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); } public function SetLinearDamping(linearDamping:Number):void{ m_linearDamping = linearDamping; } public function PutToSleep():void{ m_flags = (m_flags | e_sleepFlag); m_sleepTime = 0; m_linearVelocity.SetZero(); m_angularVelocity = 0; m_force.SetZero(); m_torque = 0; } public function GetControllerList():b2ControllerEdge{ return (m_controllerList); } public function SetMassFromShapes():void{ var s:b2Shape; if (m_world.m_lock == true){ return; }; m_mass = 0; m_invMass = 0; m_I = 0; m_invI = 0; var centerX:Number = 0; var centerY:Number = 0; var massData:b2MassData = s_massData; s = m_shapeList; while (s) { s.ComputeMass(massData); m_mass = (m_mass + massData.mass); centerX = (centerX + (massData.mass * massData.center.x)); centerY = (centerY + (massData.mass * massData.center.y)); m_I = (m_I + massData.I); s = s.m_next; }; if (m_mass > 0){ m_invMass = (1 / m_mass); centerX = (centerX * m_invMass); centerY = (centerY * m_invMass); }; if ((((m_I > 0)) && (((m_flags & e_fixedRotationFlag) == 0)))){ m_I = (m_I - (m_mass * ((centerX * centerX) + (centerY * centerY)))); m_invI = (1 / m_I); } else { m_I = 0; m_invI = 0; }; m_sweep.localCenter.Set(centerX, centerY); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); s = m_shapeList; while (s) { s.UpdateSweepRadius(m_sweep.localCenter); s = s.m_next; }; var oldType:int = m_type; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; if (oldType != m_type){ s = m_shapeList; while (s) { s.RefilterProxy(m_world.m_broadPhase, m_xf); s = s.m_next; }; }; } public function SetXForm(position:b2Vec2, angle:Number):Boolean{ var s:b2Shape; var inRange:Boolean; if (m_world.m_lock == true){ return (true); }; if (IsFrozen()){ return (false); }; m_xf.R.Set(angle); m_xf.position.SetV(position); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); m_sweep.a0 = (m_sweep.a = angle); var freeze:Boolean; s = m_shapeList; while (s) { inRange = s.Synchronize(m_world.m_broadPhase, m_xf, m_xf); if (inRange == false){ freeze = true; break; }; s = s.m_next; }; if (freeze == true){ m_flags = (m_flags | e_frozenFlag); m_linearVelocity.SetZero(); m_angularVelocity = 0; s = m_shapeList; while (s) { s.DestroyProxy(m_world.m_broadPhase); s = s.m_next; }; return (false); }; m_world.m_broadPhase.Commit(); return (true); } public function SetAngularVelocity(omega:Number):void{ m_angularVelocity = omega; } b2internal function SynchronizeShapes():Boolean{ var s:b2Shape; var xf1:b2XForm = s_xf1; xf1.R.Set(m_sweep.a0); var tMat:b2Mat22 = xf1.R; var tVec:b2Vec2 = m_sweep.localCenter; xf1.position.x = (m_sweep.c0.x - ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); xf1.position.y = (m_sweep.c0.y - ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); var inRange:Boolean; s = m_shapeList; while (s) { inRange = s.Synchronize(m_world.m_broadPhase, xf1, m_xf); if (inRange == false){ break; }; s = s.m_next; }; if (inRange == false){ m_flags = (m_flags | e_frozenFlag); m_linearVelocity.SetZero(); m_angularVelocity = 0; s = m_shapeList; while (s) { s.DestroyProxy(m_world.m_broadPhase); s = s.m_next; }; return (false); }; return (true); } public function GetAngle():Number{ return (m_sweep.a); } public function GetLinearVelocityFromLocalPoint(localPoint:b2Vec2):b2Vec2{ var A:b2Mat22 = m_xf.R; var worldPoint:b2Vec2 = new b2Vec2(((A.col1.x * localPoint.x) + (A.col2.x * localPoint.y)), ((A.col1.y * localPoint.x) + (A.col2.y * localPoint.y))); worldPoint.x = (worldPoint.x + m_xf.position.x); worldPoint.y = (worldPoint.y + m_xf.position.y); return (new b2Vec2((m_linearVelocity.x - (m_angularVelocity * (worldPoint.y - m_sweep.c.y))), (m_linearVelocity.y + (m_angularVelocity * (worldPoint.x - m_sweep.c.x))))); } public function GetNext():b2Body{ return (m_next); } public function GetMass():Number{ return (m_mass); } public function ApplyForce(force:b2Vec2, point:b2Vec2):void{ if (IsSleeping()){ WakeUp(); }; m_force.x = (m_force.x + force.x); m_force.y = (m_force.y + force.y); m_torque = (m_torque + (((point.x - m_sweep.c.x) * force.y) - ((point.y - m_sweep.c.y) * force.x))); } public function SetStatic():void{ if (m_type == e_staticType){ return; }; m_mass = 0; m_invMass = 0; m_I = 0; m_invI = 0; m_type = e_staticType; var s:b2Shape = m_shapeList; while (s) { s.RefilterProxy(m_world.m_broadPhase, m_xf); s = s.m_next; }; } public function SetMass(massData:b2MassData):void{ var s:b2Shape; if (m_world.m_lock == true){ return; }; m_invMass = 0; m_I = 0; m_invI = 0; m_mass = massData.mass; if (m_mass > 0){ m_invMass = (1 / m_mass); }; if ((m_flags & b2Body.e_fixedRotationFlag) == 0){ m_I = massData.I; }; if (m_I > 0){ m_invI = (1 / m_I); }; m_sweep.localCenter.SetV(massData.center); var tMat:b2Mat22 = m_xf.R; var tVec:b2Vec2 = m_sweep.localCenter; m_sweep.c.x = ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y)); m_sweep.c.y = ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y)); m_sweep.c.x = (m_sweep.c.x + m_xf.position.x); m_sweep.c.y = (m_sweep.c.y + m_xf.position.y); m_sweep.c0.SetV(m_sweep.c); s = m_shapeList; while (s) { s.UpdateSweepRadius(m_sweep.localCenter); s = s.m_next; }; var oldType:int = m_type; if ((((m_invMass == 0)) && ((m_invI == 0)))){ m_type = e_staticType; } else { m_type = e_dynamicType; }; if (oldType != m_type){ s = m_shapeList; while (s) { s.RefilterProxy(m_world.m_broadPhase, m_xf); s = s.m_next; }; }; } public function IsStatic():Boolean{ return ((m_type == e_staticType)); } public function GetWorldVector(localVector:b2Vec2):b2Vec2{ return (b2Math.b2MulMV(m_xf.R, localVector)); } public function GetShapeList():b2Shape{ return (m_shapeList); } b2internal function Advance(t:Number):void{ m_sweep.Advance(t); m_sweep.c.SetV(m_sweep.c0); m_sweep.a = m_sweep.a0; SynchronizeTransform(); } public function GetUserData(){ return (m_userData); } public function GetWorldCenter():b2Vec2{ return (m_sweep.c); } public function SetUserData(data):void{ m_userData = data; } public function GetLocalVector(worldVector:b2Vec2):b2Vec2{ return (b2Math.b2MulTMV(m_xf.R, worldVector)); } public function WakeUp():void{ m_flags = (m_flags & ~(e_sleepFlag)); m_sleepTime = 0; } public function GetLinearVelocityFromWorldPoint(worldPoint:b2Vec2):b2Vec2{ return (new b2Vec2((m_linearVelocity.x - (m_angularVelocity * (worldPoint.y - m_sweep.c.y))), (m_linearVelocity.y + (m_angularVelocity * (worldPoint.x - m_sweep.c.x))))); } public function GetLinearDamping():Number{ return (m_linearDamping); } public function GetLocalCenter():b2Vec2{ return (m_sweep.localCenter); } private function connectEdges(s1:b2EdgeShape, s2:b2EdgeShape, angle1:Number):Number{ var angle2:Number = Math.atan2(s2.GetDirectionVector().y, s2.GetDirectionVector().x); var coreOffset:Number = Math.tan(((angle2 - angle1) * 0.5)); var core:b2Vec2 = b2Math.MulFV(coreOffset, s2.GetDirectionVector()); core = b2Math.SubtractVV(core, s2.GetNormalVector()); core = b2Math.MulFV(b2Settings.b2_toiSlop, core); core = b2Math.AddVV(core, s2.GetVertex1()); var cornerDir:b2Vec2 = b2Math.AddVV(s1.GetDirectionVector(), s2.GetDirectionVector()); cornerDir.Normalize(); var convex = (b2Math.b2Dot(s1.GetDirectionVector(), s2.GetNormalVector()) > 0); s1.SetNextEdge(s2, core, cornerDir, convex); s2.SetPrevEdge(s1, core, cornerDir, convex); return (angle2); } public function GetPosition():b2Vec2{ return (m_xf.position); } public function IsFrozen():Boolean{ return (((m_flags & e_frozenFlag) == e_frozenFlag)); } public function IsDynamic():Boolean{ return ((m_type == e_dynamicType)); } public function GetAngularDamping():Number{ return (m_angularDamping); } public function SetAngularDamping(angularDamping:Number):void{ m_angularDamping = angularDamping; } public function GetInertia():Number{ return (m_I); } public function GetJointList():b2JointEdge{ return (m_jointList); } public function GetLocalPoint(worldPoint:b2Vec2):b2Vec2{ return (b2Math.b2MulXT(m_xf, worldPoint)); } public function GetXForm():b2XForm{ return (m_xf); } public function ApplyImpulse(impulse:b2Vec2, point:b2Vec2):void{ if (IsSleeping()){ WakeUp(); }; m_linearVelocity.x = (m_linearVelocity.x + (m_invMass * impulse.x)); m_linearVelocity.y = (m_linearVelocity.y + (m_invMass * impulse.y)); m_angularVelocity = (m_angularVelocity + (m_invI * (((point.x - m_sweep.c.x) * impulse.y) - ((point.y - m_sweep.c.y) * impulse.x)))); } public function GetAngularVelocity():Number{ return (m_angularVelocity); } b2internal function IsConnected(other:b2Body):Boolean{ var jn:b2JointEdge = m_jointList; while (jn) { if (jn.other == other){ return ((jn.joint.m_collideConnected == false)); }; jn = jn.next; }; return (false); } public function SetBullet(flag:Boolean):void{ if (flag){ m_flags = (m_flags | e_bulletFlag); } else { m_flags = (m_flags & ~(e_bulletFlag)); }; } public function CreateShape(def:b2ShapeDef):b2Shape{ var edgeDef:b2EdgeChainDef; var v1:b2Vec2; var v2:b2Vec2; var i:int; var s0:b2EdgeShape; var s1:b2EdgeShape; var s2:b2EdgeShape; var angle:Number; if (m_world.m_lock == true){ return (null); }; if (def.type == b2Shape.e_edgeShape){ edgeDef = (def as b2EdgeChainDef); if (edgeDef.isALoop){ v1 = edgeDef.vertices[(edgeDef.vertexCount - 1)]; i = 0; } else { v1 = edgeDef.vertices[0]; i = 1; }; s0 = null; s1 = null; s2 = null; angle = 0; while (i < edgeDef.vertexCount) { v2 = edgeDef.vertices[i]; s2 = new b2EdgeShape(v1, v2, def); s2.m_next = m_shapeList; m_shapeList = s2; m_shapeCount++; s2.m_body = this; s2.CreateProxy(m_world.m_broadPhase, m_xf); s2.UpdateSweepRadius(m_sweep.localCenter); if (s1 == null){ s0 = s2; angle = Math.atan2(s2.GetDirectionVector().y, s2.GetDirectionVector().x); } else { angle = connectEdges(s1, s2, angle); }; s1 = s2; v1 = v2; i++; }; if (edgeDef.isALoop){ connectEdges(s1, s0, angle); }; return (s0); }; var s:b2Shape = b2Shape.Create(def, m_world.m_blockAllocator); s.m_next = m_shapeList; m_shapeList = s; m_shapeCount++; s.m_body = this; s.CreateProxy(m_world.m_broadPhase, m_xf); s.UpdateSweepRadius(m_sweep.localCenter); return (s); } public function DestroyShape(s:b2Shape):void{ if (m_world.m_lock == true){ return; }; s.DestroyProxy(m_world.m_broadPhase); var node:b2Shape = m_shapeList; var ppS:b2Shape; var found:Boolean; while (node != null) { if (node == s){ if (ppS){ ppS.m_next = s.m_next; } else { m_shapeList = s.m_next; }; found = true; break; }; ppS = node; node = node.m_next; }; s.m_body = null; s.m_next = null; m_shapeCount--; b2Shape.Destroy(s, m_world.m_blockAllocator); } public function IsFixedRotation():Boolean{ return (((m_flags & e_fixedRotationFlag) == e_fixedRotationFlag)); } public function IsAllowSleeping():Boolean{ return (((m_flags & e_allowSleepFlag) == e_allowSleepFlag)); } public function SetFixedRotation(fixed:Boolean):void{ if (fixed){ m_angularVelocity = 0; m_invI = 0; m_flags = (m_flags | e_fixedRotationFlag); } else { if (m_I > 0){ m_invI = (1 / m_I); m_flags = (m_flags & e_fixedRotationFlag); }; }; } public function IsBullet():Boolean{ return (((m_flags & e_bulletFlag) == e_bulletFlag)); } public function GetWorldPoint(localPoint:b2Vec2):b2Vec2{ var A:b2Mat22 = m_xf.R; var u:b2Vec2 = new b2Vec2(((A.col1.x * localPoint.x) + (A.col2.x * localPoint.y)), ((A.col1.y * localPoint.x) + (A.col2.y * localPoint.y))); u.x = (u.x + m_xf.position.x); u.y = (u.y + m_xf.position.y); return (u); } public function ApplyTorque(torque:Number):void{ if (IsSleeping()){ WakeUp(); }; m_torque = (m_torque + torque); } public function AllowSleeping(flag:Boolean):void{ if (flag){ m_flags = (m_flags | e_allowSleepFlag); } else { m_flags = (m_flags & ~(e_allowSleepFlag)); WakeUp(); }; } public function GetWorld():b2World{ return (m_world); } public function GetLinearVelocity():b2Vec2{ return (m_linearVelocity); } } }//package Box2D.Dynamics
Section 75
//b2BodyDef (Box2D.Dynamics.b2BodyDef) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class b2BodyDef { public var angularDamping:Number; public var angle:Number; public var isSleeping:Boolean; public var position:b2Vec2; public var isBullet:Boolean; public var allowSleep:Boolean; public var userData; public var fixedRotation:Boolean; public var linearDamping:Number; public var massData:b2MassData; public function b2BodyDef(){ massData = new b2MassData(); position = new b2Vec2(); super(); massData.center.SetZero(); massData.mass = 0; massData.I = 0; userData = null; position.Set(0, 0); angle = 0; linearDamping = 0; angularDamping = 0; allowSleep = true; isSleeping = false; fixedRotation = false; isBullet = false; } } }//package Box2D.Dynamics
Section 76
//b2BoundaryListener (Box2D.Dynamics.b2BoundaryListener) package Box2D.Dynamics { public class b2BoundaryListener { public function b2BoundaryListener(){ super(); } public function Violation(body:b2Body):void{ } } }//package Box2D.Dynamics
Section 77
//b2ContactFilter (Box2D.Dynamics.b2ContactFilter) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Common.*; public class b2ContactFilter { b2internal static var b2_defaultFilter:b2ContactFilter = new (b2ContactFilter); ; public function b2ContactFilter(){ super(); } public function ShouldCollide(shape1:b2Shape, shape2:b2Shape):Boolean{ var filter1:b2FilterData = shape1.GetFilterData(); var filter2:b2FilterData = shape2.GetFilterData(); if ((((filter1.groupIndex == filter2.groupIndex)) && (!((filter1.groupIndex == 0))))){ return ((filter1.groupIndex > 0)); }; var collide:Boolean = ((!(((filter1.maskBits & filter2.categoryBits) == 0))) && (!(((filter1.categoryBits & filter2.maskBits) == 0)))); return (collide); } public function RayCollide(userData, shape:b2Shape):Boolean{ if (!userData){ return (true); }; return (ShouldCollide((userData as b2Shape), shape)); } } }//package Box2D.Dynamics
Section 78
//b2ContactListener (Box2D.Dynamics.b2ContactListener) package Box2D.Dynamics { import Box2D.Collision.*; import Box2D.Dynamics.Contacts.*; public class b2ContactListener { public function b2ContactListener(){ super(); } public function Add(point:b2ContactPoint):void{ } public function Remove(point:b2ContactPoint):void{ } public function Persist(point:b2ContactPoint):void{ } public function Result(point:b2ContactResult):void{ } } }//package Box2D.Dynamics
Section 79
//b2ContactManager (Box2D.Dynamics.b2ContactManager) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Collision.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2ContactManager extends b2PairCallback { b2internal var m_world:b2World; private var m_destroyImmediate:Boolean; private var m_nullContact:b2NullContact; private static const s_evalCP:b2ContactPoint = new b2ContactPoint(); public function b2ContactManager(){ m_nullContact = new b2NullContact(); super(); m_world = null; m_destroyImmediate = false; } override public function PairRemoved(proxyUserData1, proxyUserData2, pairUserData):void{ if (pairUserData == null){ return; }; var c:b2Contact = (pairUserData as b2Contact); if (c == m_nullContact){ return; }; Destroy(c); } public function Destroy(c:b2Contact):void{ var manifolds:Array; var i:int; var manifold:b2Manifold; var j:int; var mp:b2ManifoldPoint; var v1:b2Vec2; var v2:b2Vec2; var shape1:b2Shape = c.m_shape1; var shape2:b2Shape = c.m_shape2; var body1:b2Body = shape1.m_body; var body2:b2Body = shape2.m_body; var cp:b2ContactPoint = s_evalCP; cp.shape1 = c.m_shape1; cp.shape2 = c.m_shape2; cp.friction = b2Settings.b2MixFriction(shape1.GetFriction(), shape2.GetFriction()); cp.restitution = b2Settings.b2MixRestitution(shape1.GetRestitution(), shape2.GetRestitution()); var manifoldCount:int = c.m_manifoldCount; if ((((manifoldCount > 0)) && (m_world.m_contactListener))){ manifolds = c.GetManifolds(); i = 0; while (i < manifoldCount) { manifold = manifolds[i]; cp.normal.SetV(manifold.normal); j = 0; while (j < manifold.pointCount) { mp = manifold.points[j]; cp.position = body1.GetWorldPoint(mp.localPoint1); v1 = body1.GetLinearVelocityFromLocalPoint(mp.localPoint1); v2 = body2.GetLinearVelocityFromLocalPoint(mp.localPoint2); cp.velocity.Set((v2.x - v1.x), (v2.y - v1.y)); cp.separation = mp.separation; cp.id.key = mp.id._key; m_world.m_contactListener.Remove(cp); j++; }; i++; }; }; if (c.m_prev){ c.m_prev.m_next = c.m_next; }; if (c.m_next){ c.m_next.m_prev = c.m_prev; }; if (c == m_world.m_contactList){ m_world.m_contactList = c.m_next; }; if (c.m_node1.prev){ c.m_node1.prev.next = c.m_node1.next; }; if (c.m_node1.next){ c.m_node1.next.prev = c.m_node1.prev; }; if (c.m_node1 == body1.m_contactList){ body1.m_contactList = c.m_node1.next; }; if (c.m_node2.prev){ c.m_node2.prev.next = c.m_node2.next; }; if (c.m_node2.next){ c.m_node2.next.prev = c.m_node2.prev; }; if (c.m_node2 == body2.m_contactList){ body2.m_contactList = c.m_node2.next; }; b2Contact.Destroy(c, m_world.m_blockAllocator); m_world.m_contactCount--; } override public function PairAdded(proxyUserData1, proxyUserData2){ var shape1:b2Shape = (proxyUserData1 as b2Shape); var shape2:b2Shape = (proxyUserData2 as b2Shape); var body1:b2Body = shape1.m_body; var body2:b2Body = shape2.m_body; if (((body1.IsStatic()) && (body2.IsStatic()))){ return (m_nullContact); }; if (shape1.m_body == shape2.m_body){ return (m_nullContact); }; if (body2.IsConnected(body1)){ return (m_nullContact); }; if (((!((m_world.m_contactFilter == null))) && ((m_world.m_contactFilter.ShouldCollide(shape1, shape2) == false)))){ return (m_nullContact); }; var c:b2Contact = b2Contact.Create(shape1, shape2, m_world.m_blockAllocator); if (c == null){ return (m_nullContact); }; shape1 = c.m_shape1; shape2 = c.m_shape2; body1 = shape1.m_body; body2 = shape2.m_body; c.m_prev = null; c.m_next = m_world.m_contactList; if (m_world.m_contactList != null){ m_world.m_contactList.m_prev = c; }; m_world.m_contactList = c; c.m_node1.contact = c; c.m_node1.other = body2; c.m_node1.prev = null; c.m_node1.next = body1.m_contactList; if (body1.m_contactList != null){ body1.m_contactList.prev = c.m_node1; }; body1.m_contactList = c.m_node1; c.m_node2.contact = c; c.m_node2.other = body1; c.m_node2.prev = null; c.m_node2.next = body2.m_contactList; if (body2.m_contactList != null){ body2.m_contactList.prev = c.m_node2; }; body2.m_contactList = c.m_node2; m_world.m_contactCount++; return (c); } public function Collide():void{ var body1:b2Body; var body2:b2Body; var c:b2Contact = m_world.m_contactList; while (c) { body1 = c.m_shape1.m_body; body2 = c.m_shape2.m_body; if (((body1.IsSleeping()) && (body2.IsSleeping()))){ } else { c.Update(m_world.m_contactListener); }; c = c.m_next; }; } } }//package Box2D.Dynamics
Section 80
//b2DebugDraw (Box2D.Dynamics.b2DebugDraw) package Box2D.Dynamics { import flash.display.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Collision.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2DebugDraw { private var m_xformScale:Number;// = 1 private var m_fillAlpha:Number;// = 1 private var m_alpha:Number;// = 1 private var m_lineThickness:Number;// = 1 private var m_drawFlags:uint; b2internal var m_sprite:Sprite; private var m_drawScale:Number;// = 1 public static var e_coreShapeBit:uint = 4; public static var e_shapeBit:uint = 1; public static var e_centerOfMassBit:uint = 64; public static var e_aabbBit:uint = 8; public static var e_controllerBit:uint = 128; public static var e_obbBit:uint = 16; public static var e_pairBit:uint = 32; public static var e_jointBit:uint = 2; public function b2DebugDraw(){ super(); m_drawFlags = 0; } public function SetDrawScale(drawScale:Number):void{ m_drawScale = drawScale; } public function GetFillAlpha():Number{ return (m_fillAlpha); } public function GetAlpha():Number{ return (m_alpha); } public function GetLineThickness():Number{ return (m_lineThickness); } public function GetDrawScale():Number{ return (m_drawScale); } public function DrawSolidPolygon(vertices:Array, vertexCount:int, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); m_sprite.graphics.beginFill(color.color, m_fillAlpha); var i = 1; while (i < vertexCount) { m_sprite.graphics.lineTo((vertices[i].x * m_drawScale), (vertices[i].y * m_drawScale)); i++; }; m_sprite.graphics.lineTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); m_sprite.graphics.endFill(); } public function DrawCircle(center:b2Vec2, radius:Number, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.drawCircle((center.x * m_drawScale), (center.y * m_drawScale), (radius * m_drawScale)); } public function DrawSolidCircle(center:b2Vec2, radius:Number, axis:b2Vec2, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo(0, 0); m_sprite.graphics.beginFill(color.color, m_fillAlpha); m_sprite.graphics.drawCircle((center.x * m_drawScale), (center.y * m_drawScale), (radius * m_drawScale)); m_sprite.graphics.endFill(); m_sprite.graphics.moveTo((center.x * m_drawScale), (center.y * m_drawScale)); m_sprite.graphics.lineTo(((center.x + (axis.x * radius)) * m_drawScale), ((center.y + (axis.y * radius)) * m_drawScale)); } public function DrawXForm(xf:b2XForm):void{ m_sprite.graphics.lineStyle(m_lineThickness, 0xFF0000, m_alpha); m_sprite.graphics.moveTo((xf.position.x * m_drawScale), (xf.position.y * m_drawScale)); m_sprite.graphics.lineTo(((xf.position.x + (m_xformScale * xf.R.col1.x)) * m_drawScale), ((xf.position.y + (m_xformScale * xf.R.col1.y)) * m_drawScale)); m_sprite.graphics.lineStyle(m_lineThickness, 0xFF00, m_alpha); m_sprite.graphics.moveTo((xf.position.x * m_drawScale), (xf.position.y * m_drawScale)); m_sprite.graphics.lineTo(((xf.position.x + (m_xformScale * xf.R.col2.x)) * m_drawScale), ((xf.position.y + (m_xformScale * xf.R.col2.y)) * m_drawScale)); } public function ClearFlags(flags:uint):void{ m_drawFlags = (m_drawFlags & ~(flags)); } public function GetSprite():Sprite{ return (m_sprite); } public function GetXFormScale():Number{ return (m_xformScale); } public function SetFlags(flags:uint):void{ m_drawFlags = flags; } public function SetSprite(sprite:Sprite):void{ m_sprite = sprite; } public function AppendFlags(flags:uint):void{ m_drawFlags = (m_drawFlags | flags); } public function DrawSegment(p1:b2Vec2, p2:b2Vec2, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((p1.x * m_drawScale), (p1.y * m_drawScale)); m_sprite.graphics.lineTo((p2.x * m_drawScale), (p2.y * m_drawScale)); } public function SetXFormScale(xformScale:Number):void{ m_xformScale = xformScale; } public function GetFlags():uint{ return (m_drawFlags); } public function DrawPolygon(vertices:Array, vertexCount:int, color:b2Color):void{ m_sprite.graphics.lineStyle(m_lineThickness, color.color, m_alpha); m_sprite.graphics.moveTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); var i = 1; while (i < vertexCount) { m_sprite.graphics.lineTo((vertices[i].x * m_drawScale), (vertices[i].y * m_drawScale)); i++; }; m_sprite.graphics.lineTo((vertices[0].x * m_drawScale), (vertices[0].y * m_drawScale)); } public function SetFillAlpha(alpha:Number):void{ m_fillAlpha = alpha; } public function SetAlpha(alpha:Number):void{ m_alpha = alpha; } public function SetLineThickness(lineThickness:Number):void{ m_lineThickness = lineThickness; } } }//package Box2D.Dynamics
Section 81
//b2DestructionListener (Box2D.Dynamics.b2DestructionListener) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Joints.*; public class b2DestructionListener { public function b2DestructionListener(){ super(); } public function SayGoodbyeShape(shape:b2Shape):void{ } public function SayGoodbyeJoint(joint:b2Joint):void{ } } }//package Box2D.Dynamics
Section 82
//b2Island (Box2D.Dynamics.b2Island) package Box2D.Dynamics { import Box2D.Dynamics.Joints.*; import Box2D.Common.Math.*; import Box2D.Collision.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2Island { private var m_listener:b2ContactListener; private var m_bodyCapacity:int; b2internal var m_bodies:Array; b2internal var m_joints:Array; b2internal var m_jointCapacity:int; b2internal var m_contactCount:int; b2internal var m_contacts:Array; b2internal var m_contactCapacity:int; b2internal var m_jointCount:int; private var m_allocator; b2internal var m_bodyCount:int; private static var s_reportCR:b2ContactResult = new b2ContactResult(); public function b2Island(bodyCapacity:int, contactCapacity:int, jointCapacity:int, allocator, listener:b2ContactListener){ var i:int; super(); m_bodyCapacity = bodyCapacity; m_contactCapacity = contactCapacity; m_jointCapacity = jointCapacity; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_allocator = allocator; m_listener = listener; m_bodies = new Array(bodyCapacity); i = 0; while (i < bodyCapacity) { m_bodies[i] = null; i++; }; m_contacts = new Array(contactCapacity); i = 0; while (i < contactCapacity) { m_contacts[i] = null; i++; }; m_joints = new Array(jointCapacity); i = 0; while (i < jointCapacity) { m_joints[i] = null; i++; }; } public function AddBody(body:b2Body):void{ body.m_islandIndex = m_bodyCount; var _local2 = m_bodyCount++; m_bodies[_local2] = body; } public function AddJoint(joint:b2Joint):void{ var _local2 = m_jointCount++; m_joints[_local2] = joint; } public function Report(constraints:Array):void{ var tMat:b2Mat22; var tVec:b2Vec2; var c:b2Contact; var cc:b2ContactConstraint; var cr:b2ContactResult; var b1:b2Body; var manifoldCount:int; var manifolds:Array; var j:int; var manifold:b2Manifold; var k:int; var point:b2ManifoldPoint; var ccp:b2ContactConstraintPoint; if (m_listener == null){ return; }; var i:int; while (i < m_contactCount) { c = m_contacts[i]; cc = constraints[i]; cr = s_reportCR; cr.shape1 = c.m_shape1; cr.shape2 = c.m_shape2; b1 = cr.shape1.m_body; manifoldCount = c.m_manifoldCount; manifolds = c.GetManifolds(); j = 0; while (j < manifoldCount) { manifold = manifolds[j]; cr.normal.SetV(manifold.normal); k = 0; while (k < manifold.pointCount) { point = manifold.points[k]; ccp = cc.points[k]; cr.position = b1.GetWorldPoint(point.localPoint1); cr.normalImpulse = ccp.normalImpulse; cr.tangentImpulse = ccp.tangentImpulse; cr.id.key = point.id.key; m_listener.Result(cr); k++; }; j++; }; i++; }; } public function AddContact(contact:b2Contact):void{ var _local2 = m_contactCount++; m_contacts[_local2] = contact; } public function Solve(step:b2TimeStep, gravity:b2Vec2, allowSleep:Boolean):void{ var i:int; var j:int; var b:b2Body; var joint:b2Joint; var contactsOkay:Boolean; var jointsOkay:Boolean; var jointOkay:Boolean; var minSleepTime:Number; var linTolSqr:Number; var angTolSqr:Number; i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_linearVelocity.x = (b.m_linearVelocity.x + (step.dt * (gravity.x + (b.m_invMass * b.m_force.x)))); b.m_linearVelocity.y = (b.m_linearVelocity.y + (step.dt * (gravity.y + (b.m_invMass * b.m_force.y)))); b.m_angularVelocity = (b.m_angularVelocity + ((step.dt * b.m_invI) * b.m_torque)); b.m_force.SetZero(); b.m_torque = 0; b.m_linearVelocity.Multiply(b2Math.b2Clamp((1 - (step.dt * b.m_linearDamping)), 0, 1)); b.m_angularVelocity = (b.m_angularVelocity * b2Math.b2Clamp((1 - (step.dt * b.m_angularDamping)), 0, 1)); if (b.m_linearVelocity.LengthSquared() > b2Settings.b2_maxLinearVelocitySquared){ b.m_linearVelocity.Normalize(); b.m_linearVelocity.x = (b.m_linearVelocity.x * b2Settings.b2_maxLinearVelocity); b.m_linearVelocity.y = (b.m_linearVelocity.y * b2Settings.b2_maxLinearVelocity); }; if ((b.m_angularVelocity * b.m_angularVelocity) > b2Settings.b2_maxAngularVelocitySquared){ if (b.m_angularVelocity < 0){ b.m_angularVelocity = -(b2Settings.b2_maxAngularVelocity); } else { b.m_angularVelocity = b2Settings.b2_maxAngularVelocity; }; }; }; i++; }; var contactSolver:b2ContactSolver = new b2ContactSolver(step, m_contacts, m_contactCount, m_allocator); contactSolver.InitVelocityConstraints(step); i = 0; while (i < m_jointCount) { joint = m_joints[i]; joint.InitVelocityConstraints(step); i++; }; i = 0; while (i < step.velocityIterations) { j = 0; while (j < m_jointCount) { joint = m_joints[j]; joint.SolveVelocityConstraints(step); j++; }; contactSolver.SolveVelocityConstraints(); i++; }; contactSolver.FinalizeVelocityConstraints(); i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_sweep.c0.SetV(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; b.m_sweep.c.x = (b.m_sweep.c.x + (step.dt * b.m_linearVelocity.x)); b.m_sweep.c.y = (b.m_sweep.c.y + (step.dt * b.m_linearVelocity.y)); b.m_sweep.a = (b.m_sweep.a + (step.dt * b.m_angularVelocity)); b.SynchronizeTransform(); }; i++; }; i = 0; while (i < step.positionIterations) { contactsOkay = contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte); jointsOkay = true; j = 0; while (j < m_jointCount) { joint = m_joints[j]; jointOkay = joint.SolvePositionConstraints(b2Settings.b2_contactBaumgarte); jointsOkay = ((jointsOkay) && (jointOkay)); j++; }; if (((contactsOkay) && (jointsOkay))){ break; }; i++; }; Report(contactSolver.m_constraints); if (allowSleep){ minSleepTime = Number.MAX_VALUE; linTolSqr = (b2Settings.b2_linearSleepTolerance * b2Settings.b2_linearSleepTolerance); angTolSqr = (b2Settings.b2_angularSleepTolerance * b2Settings.b2_angularSleepTolerance); i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.m_invMass == 0){ } else { if ((b.m_flags & b2Body.e_allowSleepFlag) == 0){ b.m_sleepTime = 0; minSleepTime = 0; }; if (((((((b.m_flags & b2Body.e_allowSleepFlag) == 0)) || (((b.m_angularVelocity * b.m_angularVelocity) > angTolSqr)))) || ((b2Math.b2Dot(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr)))){ b.m_sleepTime = 0; minSleepTime = 0; } else { b.m_sleepTime = (b.m_sleepTime + step.dt); minSleepTime = b2Math.b2Min(minSleepTime, b.m_sleepTime); }; }; i++; }; if (minSleepTime >= b2Settings.b2_timeToSleep){ i = 0; while (i < m_bodyCount) { b = m_bodies[i]; b.m_flags = (b.m_flags | b2Body.e_sleepFlag); b.m_linearVelocity.SetZero(); b.m_angularVelocity = 0; i++; }; }; }; } public function Clear():void{ m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; } public function SolveTOI(subStep:b2TimeStep):void{ var i:int; var j:int; var b:b2Body; var contactsOkay:Boolean; var jointsOkay:Boolean; var jointOkay:Boolean; var contactSolver:b2ContactSolver = new b2ContactSolver(subStep, m_contacts, m_contactCount, m_allocator); subStep.warmStarting = true; i = 0; while (i < m_jointCount) { m_joints[i].InitVelocityConstraints(subStep); i++; }; i = 0; while (i < subStep.velocityIterations) { contactSolver.SolveVelocityConstraints(); j = 0; while (j < m_jointCount) { m_joints[j].InitVelocityConstraints(subStep); j++; }; i++; }; i = 0; while (i < m_bodyCount) { b = m_bodies[i]; if (b.IsStatic()){ } else { b.m_sweep.c0.SetV(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; b.m_sweep.c.x = (b.m_sweep.c.x + (subStep.dt * b.m_linearVelocity.x)); b.m_sweep.c.y = (b.m_sweep.c.y + (subStep.dt * b.m_linearVelocity.y)); b.m_sweep.a = (b.m_sweep.a + (subStep.dt * b.m_angularVelocity)); b.SynchronizeTransform(); }; i++; }; var k_toiBaumgarte:Number = 0.75; i = 0; while (i < subStep.positionIterations) { contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte); jointsOkay = true; j = 0; while (j < m_jointCount) { jointOkay = m_joints[j].SolvePositionConstraints(b2Settings.b2_contactBaumgarte); jointsOkay = ((jointsOkay) && (jointOkay)); j++; }; if (((contactsOkay) && (jointsOkay))){ break; }; i++; }; Report(contactSolver.m_constraints); } } }//package Box2D.Dynamics
Section 83
//b2TimeStep (Box2D.Dynamics.b2TimeStep) package Box2D.Dynamics { public class b2TimeStep { public var warmStarting:Boolean; public var inv_dt:Number; public var dt:Number; public var velocityIterations:int; public var dtRatio:Number; public var positionIterations:int; public function b2TimeStep(){ super(); } } }//package Box2D.Dynamics
Section 84
//b2World (Box2D.Dynamics.b2World) package Box2D.Dynamics { import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Joints.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Controllers.*; import Box2D.Collision.*; import Box2D.Common.*; import Box2D.Dynamics.Contacts.*; public class b2World { private var m_inv_dt0:Number; private var m_controllerCount:int; private var m_boundaryListener:b2BoundaryListener; private var m_controllerList:b2Controller; b2internal var m_contactList:b2Contact; b2internal var m_blockAllocator; b2internal var m_contactListener:b2ContactListener; b2internal var m_raycastSegment:b2Segment; b2internal var m_broadPhase:b2BroadPhase; private var m_destructionListener:b2DestructionListener; private var m_jointCount:int; private var m_bodyCount:int; b2internal var m_lock:Boolean; b2internal var m_raycastUserData; private var m_allowSleep:Boolean; b2internal var m_groundBody:b2Body; b2internal var m_contactCount:int; b2internal var m_raycastNormal:b2Vec2; b2internal var m_contactFilter:b2ContactFilter; b2internal var m_bodyList:b2Body; private var m_debugDraw:b2DebugDraw; b2internal var m_stackAllocator; private var m_jointList:b2Joint; private var m_gravity:b2Vec2; private var m_contactManager:b2ContactManager; private static var s_xf:b2XForm = new b2XForm(); private static var s_jointColor:b2Color = new b2Color(0.5, 0.8, 0.8); private static var m_continuousPhysics:Boolean; private static var m_warmStarting:Boolean; private static var s_coreColor:b2Color = new b2Color(0.9, 0.6, 0.6); public function b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Boolean){ m_raycastNormal = new b2Vec2(); m_contactManager = new b2ContactManager(); super(); m_destructionListener = null; m_boundaryListener = null; m_contactFilter = b2ContactFilter.b2_defaultFilter; m_contactListener = null; m_debugDraw = null; m_bodyList = null; m_contactList = null; m_jointList = null; m_controllerList = null; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_controllerCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_lock = false; m_inv_dt0 = 0; m_contactManager.m_world = this; m_broadPhase = new b2BroadPhase(worldAABB, m_contactManager); var bd:b2BodyDef = new b2BodyDef(); m_groundBody = CreateBody(bd); } b2internal function DrawJoint(joint:b2Joint):void{ var pulley:b2PulleyJoint; var s1:b2Vec2; var s2:b2Vec2; var b1:b2Body = joint.m_body1; var b2:b2Body = joint.m_body2; var xf1:b2XForm = b1.m_xf; var xf2:b2XForm = b2.m_xf; var x1:b2Vec2 = xf1.position; var x2:b2Vec2 = xf2.position; var p1:b2Vec2 = joint.GetAnchor1(); var p2:b2Vec2 = joint.GetAnchor2(); var color:b2Color = s_jointColor; switch (joint.m_type){ case b2Joint.e_distanceJoint: m_debugDraw.DrawSegment(p1, p2, color); break; case b2Joint.e_pulleyJoint: pulley = (joint as b2PulleyJoint); s1 = pulley.GetGroundAnchor1(); s2 = pulley.GetGroundAnchor2(); m_debugDraw.DrawSegment(s1, p1, color); m_debugDraw.DrawSegment(s2, p2, color); m_debugDraw.DrawSegment(s1, s2, color); break; case b2Joint.e_mouseJoint: m_debugDraw.DrawSegment(p1, p2, color); break; default: if (b1 != m_groundBody){ m_debugDraw.DrawSegment(x1, p1, color); }; m_debugDraw.DrawSegment(p1, p2, color); if (b2 != m_groundBody){ m_debugDraw.DrawSegment(x2, p2, color); }; }; } public function Refilter(shape:b2Shape):void{ shape.RefilterProxy(m_broadPhase, shape.m_body.m_xf); } public function SetDebugDraw(debugDraw:b2DebugDraw):void{ m_debugDraw = debugDraw; } public function SetContinuousPhysics(flag:Boolean):void{ m_continuousPhysics = flag; } public function GetProxyCount():int{ return (m_broadPhase.m_proxyCount); } b2internal function DrawDebugData():void{ var i:int; var b:b2Body; var s:b2Shape; var j:b2Joint; var bp:b2BroadPhase; var xf:b2XForm; var core:Boolean; var c:b2Controller; var pair:b2Pair; var p1:b2Proxy; var p2:b2Proxy; var worldLower:b2Vec2; var worldUpper:b2Vec2; var p:b2Proxy; var poly:b2PolygonShape; var obb:b2OBB; var h:b2Vec2; var tMat:b2Mat22; var tVec:b2Vec2; var tX:Number; if (m_debugDraw == null){ return; }; m_debugDraw.m_sprite.graphics.clear(); var flags:uint = m_debugDraw.GetFlags(); var invQ:b2Vec2 = new b2Vec2(); var x1:b2Vec2 = new b2Vec2(); var x2:b2Vec2 = new b2Vec2(); var color:b2Color = new b2Color(0, 0, 0); var b1:b2AABB = new b2AABB(); var b2:b2AABB = new b2AABB(); var vs:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()]; if ((flags & b2DebugDraw.e_shapeBit)){ core = ((flags & b2DebugDraw.e_coreShapeBit) == b2DebugDraw.e_coreShapeBit); b = m_bodyList; while (b) { xf = b.m_xf; s = b.GetShapeList(); while (s) { if (b.IsStatic()){ DrawShape(s, xf, new b2Color(0.5, 0.9, 0.5), core); } else { if (b.IsSleeping()){ DrawShape(s, xf, new b2Color(0.5, 0.5, 0.9), core); } else { DrawShape(s, xf, new b2Color(0.9, 0.9, 0.9), core); }; }; s = s.m_next; }; b = b.m_next; }; }; if ((flags & b2DebugDraw.e_jointBit)){ j = m_jointList; while (j) { DrawJoint(j); j = j.m_next; }; }; if ((flags & b2DebugDraw.e_controllerBit)){ c = m_controllerList; while (c) { c.Draw(m_debugDraw); c = c.m_next; }; }; if ((flags & b2DebugDraw.e_pairBit)){ bp = m_broadPhase; invQ.Set((1 / bp.m_quantizationFactor.x), (1 / bp.m_quantizationFactor.y)); color.Set(0.9, 0.9, 0.3); for each (pair in bp.m_pairManager.m_pairs) { p1 = pair.proxy1; p2 = pair.proxy2; if (((!(p1)) || (!(p2)))){ } else { b1.lowerBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p1.lowerBounds[0]].value)); b1.lowerBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p1.lowerBounds[1]].value)); b1.upperBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p1.upperBounds[0]].value)); b1.upperBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p1.upperBounds[1]].value)); b2.lowerBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p2.lowerBounds[0]].value)); b2.lowerBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p2.lowerBounds[1]].value)); b2.upperBound.x = (bp.m_worldAABB.lowerBound.x + (invQ.x * bp.m_bounds[0][p2.upperBounds[0]].value)); b2.upperBound.y = (bp.m_worldAABB.lowerBound.y + (invQ.y * bp.m_bounds[1][p2.upperBounds[1]].value)); x1.x = (0.5 * (b1.lowerBound.x + b1.upperBound.x)); x1.y = (0.5 * (b1.lowerBound.y + b1.upperBound.y)); x2.x = (0.5 * (b2.lowerBound.x + b2.upperBound.x)); x2.y = (0.5 * (b2.lowerBound.y + b2.upperBound.y)); m_debugDraw.DrawSegment(x1, x2, color); }; }; }; if ((flags & b2DebugDraw.e_aabbBit)){ bp = m_broadPhase; worldLower = bp.m_worldAABB.lowerBound; worldUpper = bp.m_worldAABB.upperBound; invQ.Set((1 / bp.m_quantizationFactor.x), (1 / bp.m_quantizationFactor.y)); color.Set(0.9, 0.3, 0.9); i = 0; while (i < bp.m_proxyPool.length) { p = bp.m_proxyPool[i]; if (p.IsValid() == false){ } else { b1.lowerBound.x = (worldLower.x + (invQ.x * bp.m_bounds[0][p.lowerBounds[0]].value)); b1.lowerBound.y = (worldLower.y + (invQ.y * bp.m_bounds[1][p.lowerBounds[1]].value)); b1.upperBound.x = (worldLower.x + (invQ.x * bp.m_bounds[0][p.upperBounds[0]].value)); b1.upperBound.y = (worldLower.y + (invQ.y * bp.m_bounds[1][p.upperBounds[1]].value)); vs[0].Set(b1.lowerBound.x, b1.lowerBound.y); vs[1].Set(b1.upperBound.x, b1.lowerBound.y); vs[2].Set(b1.upperBound.x, b1.upperBound.y); vs[3].Set(b1.lowerBound.x, b1.upperBound.y); m_debugDraw.DrawPolygon(vs, 4, color); }; i++; }; vs[0].Set(worldLower.x, worldLower.y); vs[1].Set(worldUpper.x, worldLower.y); vs[2].Set(worldUpper.x, worldUpper.y); vs[3].Set(worldLower.x, worldUpper.y); m_debugDraw.DrawPolygon(vs, 4, new b2Color(0.3, 0.9, 0.9)); }; if ((flags & b2DebugDraw.e_obbBit)){ color.Set(0.5, 0.3, 0.5); b = m_bodyList; while (b) { xf = b.m_xf; s = b.GetShapeList(); while (s) { if (s.m_type != b2Shape.e_polygonShape){ } else { poly = (s as b2PolygonShape); obb = poly.GetOBB(); h = obb.extents; vs[0].Set(-(h.x), -(h.y)); vs[1].Set(h.x, -(h.y)); vs[2].Set(h.x, h.y); vs[3].Set(-(h.x), h.y); i = 0; while (i < 4) { tMat = obb.R; tVec = vs[i]; tX = (obb.center.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); vs[i].y = (obb.center.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); vs[i].x = tX; tMat = xf.R; tX = (xf.position.x + ((tMat.col1.x * tVec.x) + (tMat.col2.x * tVec.y))); vs[i].y = (xf.position.y + ((tMat.col1.y * tVec.x) + (tMat.col2.y * tVec.y))); vs[i].x = tX; i++; }; m_debugDraw.DrawPolygon(vs, 4, color); }; s = s.m_next; }; b = b.m_next; }; }; if ((flags & b2DebugDraw.e_centerOfMassBit)){ b = m_bodyList; while (b) { xf = s_xf; xf.R = b.m_xf.R; xf.position = b.GetWorldCenter(); m_debugDraw.DrawXForm(xf); b = b.m_next; }; }; } public function DestroyBody(b:b2Body):void{ var jn0:b2JointEdge; var ce0:b2ControllerEdge; var s0:b2Shape; if (m_lock == true){ return; }; var jn:b2JointEdge = b.m_jointList; while (jn) { jn0 = jn; jn = jn.next; if (m_destructionListener){ m_destructionListener.SayGoodbyeJoint(jn0.joint); }; DestroyJoint(jn0.joint); }; var ce:b2ControllerEdge = b.m_controllerList; while (ce) { ce0 = ce; ce = ce.nextController; ce0.controller.RemoveBody(b); }; var s:b2Shape = b.m_shapeList; while (s) { s0 = s; s = s.m_next; if (m_destructionListener){ m_destructionListener.SayGoodbyeShape(s0); }; s0.DestroyProxy(m_broadPhase); b2Shape.Destroy(s0, m_blockAllocator); }; if (b.m_prev){ b.m_prev.m_next = b.m_next; }; if (b.m_next){ b.m_next.m_prev = b.m_prev; }; if (b == m_bodyList){ m_bodyList = b.m_next; }; m_bodyCount--; } b2internal function DrawShape(shape:b2Shape, xf:b2XForm, color:b2Color, core:Boolean):void{ var circle:b2CircleShape; var center:b2Vec2; var radius:Number; var axis:b2Vec2; var i:int; var poly:b2PolygonShape; var vertexCount:int; var localVertices:Array; var vertices:Array; var localCoreVertices:Array; var edge:b2EdgeShape; var coreColor:b2Color = s_coreColor; switch (shape.m_type){ case b2Shape.e_circleShape: circle = (shape as b2CircleShape); center = b2Math.b2MulX(xf, circle.m_localPosition); radius = circle.m_radius; axis = xf.R.col1; m_debugDraw.DrawSolidCircle(center, radius, axis, color); if (core){ m_debugDraw.DrawCircle(center, (radius - b2Settings.b2_toiSlop), coreColor); }; break; case b2Shape.e_polygonShape: poly = (shape as b2PolygonShape); vertexCount = poly.GetVertexCount(); localVertices = poly.GetVertices(); vertices = new Array(b2Settings.b2_maxPolygonVertices); i = 0; while (i < vertexCount) { vertices[i] = b2Math.b2MulX(xf, localVertices[i]); i++; }; m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); if (core){ localCoreVertices = poly.GetCoreVertices(); i = 0; while (i < vertexCount) { vertices[i] = b2Math.b2MulX(xf, localCoreVertices[i]); i++; }; m_debugDraw.DrawPolygon(vertices, vertexCount, coreColor); }; break; case b2Shape.e_edgeShape: edge = (shape as b2EdgeShape); m_debugDraw.DrawSegment(b2Math.b2MulX(xf, edge.GetVertex1()), b2Math.b2MulX(xf, edge.GetVertex2()), color); if (core){ m_debugDraw.DrawSegment(b2Math.b2MulX(xf, edge.GetCoreVertex1()), b2Math.b2MulX(xf, edge.GetCoreVertex2()), coreColor); }; break; }; } public function GetGroundBody():b2Body{ return (m_groundBody); } public function DestroyController(controller:b2Controller):void{ controller.Clear(); if (controller.m_next){ controller.m_next.m_prev = controller.m_prev; }; if (controller.m_prev){ controller.m_prev.m_next = controller.m_next; }; if (controller == m_controllerList){ m_controllerList = controller.m_next; }; m_controllerCount--; } b2internal function Solve(step:b2TimeStep):void{ var b:b2Body; var stackCount:int; var i:int; var other:b2Body; var cn:b2ContactEdge; var jn:b2JointEdge; var inRange:Boolean; var controller:b2Controller = m_controllerList; while (controller) { controller.Step(step); controller = controller.m_next; }; var island:b2Island = new b2Island(m_bodyCount, m_contactCount, m_jointCount, m_stackAllocator, m_contactListener); b = m_bodyList; while (b) { b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); b = b.m_next; }; var c:b2Contact = m_contactList; while (c) { c.m_flags = (c.m_flags & ~(b2Contact.e_islandFlag)); c = c.m_next; }; var j:b2Joint = m_jointList; while (j) { j.m_islandFlag = false; j = j.m_next; }; var stackSize:int = m_bodyCount; var stack:Array = new Array(stackSize); var seed:b2Body = m_bodyList; while (seed) { if ((seed.m_flags & ((b2Body.e_islandFlag | b2Body.e_sleepFlag) | b2Body.e_frozenFlag))){ } else { if (seed.IsStatic()){ } else { island.Clear(); stackCount = 0; var _temp1 = stackCount; stackCount = (stackCount + 1); var _local16 = _temp1; stack[_local16] = seed; seed.m_flags = (seed.m_flags | b2Body.e_islandFlag); while (stackCount > 0) { --stackCount; b = stack[stackCount]; island.AddBody(b); b.m_flags = (b.m_flags & ~(b2Body.e_sleepFlag)); if (b.IsStatic()){ } else { cn = b.m_contactList; while (cn) { if ((cn.contact.m_flags & (b2Contact.e_islandFlag | b2Contact.e_nonSolidFlag))){ } else { if (cn.contact.m_manifoldCount == 0){ } else { island.AddContact(cn.contact); cn.contact.m_flags = (cn.contact.m_flags | b2Contact.e_islandFlag); other = cn.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { var _temp2 = stackCount; stackCount = (stackCount + 1); var _local17 = _temp2; stack[_local17] = other; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; }; cn = cn.next; }; jn = b.m_jointList; while (jn) { if (jn.joint.m_islandFlag == true){ } else { island.AddJoint(jn.joint); jn.joint.m_islandFlag = true; other = jn.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { var _temp3 = stackCount; stackCount = (stackCount + 1); _local17 = _temp3; stack[_local17] = other; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; jn = jn.next; }; }; }; island.Solve(step, m_gravity, m_allowSleep); i = 0; while (i < island.m_bodyCount) { b = island.m_bodies[i]; if (b.IsStatic()){ b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); }; i++; }; }; }; seed = seed.m_next; }; b = m_bodyList; while (b) { if ((b.m_flags & (b2Body.e_sleepFlag | b2Body.e_frozenFlag))){ } else { if (b.IsStatic()){ } else { inRange = b.SynchronizeShapes(); if ((((inRange == false)) && (!((m_boundaryListener == null))))){ m_boundaryListener.Violation(b); }; }; }; b = b.m_next; }; m_broadPhase.Commit(); } public function Query(aabb:b2AABB, shapes:Array, maxCount:int):int{ var results:Array = new Array(maxCount); var count:int = m_broadPhase.QueryAABB(aabb, results, maxCount); var i:int; while (i < count) { shapes[i] = results[i]; i++; }; return (count); } public function GetContactCount():int{ return (m_contactCount); } public function SetContactFilter(filter:b2ContactFilter):void{ m_contactFilter = filter; } b2internal function SolveTOI(step:b2TimeStep):void{ var b:b2Body; var s1:b2Shape; var s2:b2Shape; var b1:b2Body; var b2:b2Body; var cEdge:b2ContactEdge; var j:b2Joint; var c:b2Contact; var minContact:b2Contact; var minTOI:Number; var seed:b2Body; var queueStart:int; var queueSize:int; var jEdge:b2JointEdge; var subStep:b2TimeStep; var i:int; var toi:Number; var t0:Number; var other:b2Body; var inRange:Boolean; var island:b2Island = new b2Island(m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, m_stackAllocator, m_contactListener); var queueCapacity:int = m_bodyCount; var queue:Array = new Array(queueCapacity); b = m_bodyList; while (b) { b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); b.m_sweep.t0 = 0; b = b.m_next; }; c = m_contactList; while (c) { c.m_flags = (c.m_flags & ~((b2Contact.e_toiFlag | b2Contact.e_islandFlag))); c = c.m_next; }; j = m_jointList; while (j) { j.m_islandFlag = false; j = j.m_next; }; while (true) { minContact = null; minTOI = 1; c = m_contactList; for (;c;(c = c.m_next)) { if ((c.m_flags & (b2Contact.e_slowFlag | b2Contact.e_nonSolidFlag))){ } else { toi = 1; if ((c.m_flags & b2Contact.e_toiFlag)){ toi = c.m_toi; } else { s1 = c.m_shape1; s2 = c.m_shape2; b1 = s1.m_body; b2 = s2.m_body; if (((((b1.IsStatic()) || (b1.IsSleeping()))) && (((b2.IsStatic()) || (b2.IsSleeping()))))){ continue; }; t0 = b1.m_sweep.t0; if (b1.m_sweep.t0 < b2.m_sweep.t0){ t0 = b2.m_sweep.t0; b1.m_sweep.Advance(t0); } else { if (b2.m_sweep.t0 < b1.m_sweep.t0){ t0 = b1.m_sweep.t0; b2.m_sweep.Advance(t0); }; }; toi = b2TimeOfImpact.TimeOfImpact(c.m_shape1, b1.m_sweep, c.m_shape2, b2.m_sweep); if ((((toi > 0)) && ((toi < 1)))){ toi = (((1 - toi) * t0) + toi); if (toi > 1){ toi = 1; }; }; c.m_toi = toi; c.m_flags = (c.m_flags | b2Contact.e_toiFlag); }; if ((((Number.MIN_VALUE < toi)) && ((toi < minTOI)))){ minContact = c; minTOI = toi; }; }; }; if ((((minContact == null)) || (((1 - (100 * Number.MIN_VALUE)) < minTOI)))){ break; }; s1 = minContact.m_shape1; s2 = minContact.m_shape2; b1 = s1.m_body; b2 = s2.m_body; b1.Advance(minTOI); b2.Advance(minTOI); minContact.Update(m_contactListener); minContact.m_flags = (minContact.m_flags & ~(b2Contact.e_toiFlag)); if (minContact.m_manifoldCount == 0){ } else { seed = b1; if (seed.IsStatic()){ seed = b2; }; island.Clear(); queueStart = 0; queueSize = 0; var _temp1 = queueSize; queueSize = (queueSize + 1); queue[(queueStart + _temp1)] = seed; seed.m_flags = (seed.m_flags | b2Body.e_islandFlag); while (queueSize > 0) { var _temp2 = queueStart; queueStart = (queueStart + 1); b = queue[_temp2]; queueSize--; island.AddBody(b); b.m_flags = (b.m_flags & ~(b2Body.e_sleepFlag)); if (b.IsStatic()){ } else { cEdge = b.m_contactList; while (cEdge) { if (island.m_contactCount == island.m_contactCapacity){ } else { if ((cEdge.contact.m_flags & ((b2Contact.e_islandFlag | b2Contact.e_slowFlag) | b2Contact.e_nonSolidFlag))){ } else { if (cEdge.contact.m_manifoldCount == 0){ } else { island.AddContact(cEdge.contact); cEdge.contact.m_flags = (cEdge.contact.m_flags | b2Contact.e_islandFlag); other = cEdge.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { if (other.IsStatic() == false){ other.Advance(minTOI); other.WakeUp(); }; queue[(queueStart + queueSize)] = other; queueSize++; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; }; }; cEdge = cEdge.next; }; }; }; jEdge = b.m_jointList; while (jEdge) { if (island.m_jointCount == island.m_jointCapacity){ } else { if (jEdge.joint.m_islandFlag == true){ } else { island.AddJoint(jEdge.joint); jEdge.joint.m_islandFlag = true; other = jEdge.other; if ((other.m_flags & b2Body.e_islandFlag)){ } else { if (!other.IsStatic()){ other.Advance(minTOI); other.WakeUp(); }; queue[(queueStart + queueSize)] = other; queueSize++; other.m_flags = (other.m_flags | b2Body.e_islandFlag); }; }; }; jEdge = jEdge.next; }; subStep = new b2TimeStep(); subStep.warmStarting = false; subStep.dt = ((1 - minTOI) * step.dt); subStep.inv_dt = (1 / subStep.dt); subStep.dtRatio = 0; subStep.velocityIterations = step.velocityIterations; subStep.positionIterations = step.positionIterations; island.SolveTOI(subStep); i = 0; while (i < island.m_bodyCount) { b = island.m_bodies[i]; b.m_flags = (b.m_flags & ~(b2Body.e_islandFlag)); if ((b.m_flags & (b2Body.e_sleepFlag | b2Body.e_frozenFlag))){ } else { if (b.IsStatic()){ } else { inRange = b.SynchronizeShapes(); if ((((inRange == false)) && (!((m_boundaryListener == null))))){ m_boundaryListener.Violation(b); }; cEdge = b.m_contactList; while (cEdge) { cEdge.contact.m_flags = (cEdge.contact.m_flags & ~(b2Contact.e_toiFlag)); cEdge = cEdge.next; }; }; }; i++; }; i = 0; while (i < island.m_contactCount) { c = island.m_contacts[i]; c.m_flags = (c.m_flags & ~((b2Contact.e_toiFlag | b2Contact.e_islandFlag))); i++; }; i = 0; while (i < island.m_jointCount) { j = island.m_joints[i]; j.m_islandFlag = false; i++; }; m_broadPhase.Commit(); }; }; } public function GetJointList():b2Joint{ return (m_jointList); } public function SetGravity(gravity:b2Vec2):void{ m_gravity = gravity; } public function GetBodyList():b2Body{ return (m_bodyList); } public function GetGravity():b2Vec2{ return (m_gravity); } public function Validate():void{ m_broadPhase.Validate(); } public function GetPairCount():int{ return (m_broadPhase.m_pairManager.m_pairCount); } public function SetWarmStarting(flag:Boolean):void{ m_warmStarting = flag; } public function Raycast(segment:b2Segment, shapes:Array, maxCount:int, solidShapes:Boolean, userData):int{ var count:int; var results:Array = new Array(maxCount); m_raycastSegment = segment; m_raycastUserData = userData; if (solidShapes){ count = m_broadPhase.QuerySegment(segment, results, maxCount, RaycastSortKey); } else { count = m_broadPhase.QuerySegment(segment, results, maxCount, RaycastSortKey2); }; var i:int; while (i < count) { shapes[i] = results[i]; i++; }; return (count); } public function CreateJoint(def:b2JointDef):b2Joint{ var b:b2Body; var s:b2Shape; var j:b2Joint = b2Joint.Create(def, m_blockAllocator); j.m_prev = null; j.m_next = m_jointList; if (m_jointList){ m_jointList.m_prev = j; }; m_jointList = j; m_jointCount++; j.m_node1.joint = j; j.m_node1.other = j.m_body2; j.m_node1.prev = null; j.m_node1.next = j.m_body1.m_jointList; if (j.m_body1.m_jointList){ j.m_body1.m_jointList.prev = j.m_node1; }; j.m_body1.m_jointList = j.m_node1; j.m_node2.joint = j; j.m_node2.other = j.m_body1; j.m_node2.prev = null; j.m_node2.next = j.m_body2.m_jointList; if (j.m_body2.m_jointList){ j.m_body2.m_jointList.prev = j.m_node2; }; j.m_body2.m_jointList = j.m_node2; if (def.collideConnected == false){ b = ((def.body1.m_shapeCount < def.body2.m_shapeCount)) ? def.body1 : def.body2; s = b.m_shapeList; while (s) { s.RefilterProxy(m_broadPhase, b.m_xf); s = s.m_next; }; }; return (j); } public function DestroyJoint(j:b2Joint):void{ var b:b2Body; var s:b2Shape; var collideConnected:Boolean = j.m_collideConnected; if (j.m_prev){ j.m_prev.m_next = j.m_next; }; if (j.m_next){ j.m_next.m_prev = j.m_prev; }; if (j == m_jointList){ m_jointList = j.m_next; }; var body1:b2Body = j.m_body1; var body2:b2Body = j.m_body2; body1.WakeUp(); body2.WakeUp(); if (j.m_node1.prev){ j.m_node1.prev.next = j.m_node1.next; }; if (j.m_node1.next){ j.m_node1.next.prev = j.m_node1.prev; }; if (j.m_node1 == body1.m_jointList){ body1.m_jointList = j.m_node1.next; }; j.m_node1.prev = null; j.m_node1.next = null; if (j.m_node2.prev){ j.m_node2.prev.next = j.m_node2.next; }; if (j.m_node2.next){ j.m_node2.next.prev = j.m_node2.prev; }; if (j.m_node2 == body2.m_jointList){ body2.m_jointList = j.m_node2.next; }; j.m_node2.prev = null; j.m_node2.next = null; b2Joint.Destroy(j, m_blockAllocator); m_jointCount--; if (collideConnected == false){ b = ((body1.m_shapeCount < body2.m_shapeCount)) ? body1 : body2; s = b.m_shapeList; while (s) { s.RefilterProxy(m_broadPhase, b.m_xf); s = s.m_next; }; }; } public function SetContactListener(listener:b2ContactListener):void{ m_contactListener = listener; } public function CreateController(controller:b2Controller):b2Controller{ if (controller.m_world != this){ throw (new Error("Controller can only be a member of one world")); }; controller.m_next = m_controllerList; controller.m_prev = null; if (m_controllerList){ m_controllerList.m_prev = controller; }; m_controllerList = controller; m_controllerCount++; controller.m_world = this; return (controller); } b2internal function RaycastSortKey2(shape:b2Shape):Number{ if (((m_contactFilter) && (!(m_contactFilter.RayCollide(m_raycastUserData, shape))))){ return (-1); }; var body:b2Body = shape.GetBody(); var xf:b2XForm = body.GetXForm(); var lambda:Array = [0]; if (shape.TestSegment(xf, lambda, m_raycastNormal, m_raycastSegment, 1) != b2Shape.e_hitCollide){ return (-1); }; return (lambda[0]); } public function RaycastOne(segment:b2Segment, lambda:Array, normal:b2Vec2, solidShapes:Boolean, userData):b2Shape{ var shapes:Array = new Array(1); var count:Number = Raycast(segment, shapes, 1, solidShapes, userData); if (count == 0){ return (null); }; if (count > 1){ trace(count); }; var shape:b2Shape = shapes[0]; var xf:b2XForm = shape.GetBody().GetXForm(); shape.TestSegment(xf, lambda, normal, segment, 1); return (shape); } public function CreateBody(def:b2BodyDef):b2Body{ if (m_lock == true){ return (null); }; var b:b2Body = new b2Body(def, this); b.m_prev = null; b.m_next = m_bodyList; if (m_bodyList){ m_bodyList.m_prev = b; }; m_bodyList = b; m_bodyCount++; return (b); } b2internal function RaycastSortKey(shape:b2Shape):Number{ if (((m_contactFilter) && (!(m_contactFilter.RayCollide(m_raycastUserData, shape))))){ return (-1); }; var body:b2Body = shape.GetBody(); var xf:b2XForm = body.GetXForm(); var lambda:Array = [0]; if (shape.TestSegment(xf, lambda, m_raycastNormal, m_raycastSegment, 1) == b2Shape.e_missCollide){ return (-1); }; return (lambda[0]); } public function SetBoundaryListener(listener:b2BoundaryListener):void{ m_boundaryListener = listener; } public function SetDestructionListener(listener:b2DestructionListener):void{ m_destructionListener = listener; } public function RemoveController(c:b2Controller):void{ if (c.m_prev){ c.m_prev.m_next = c.m_next; }; if (c.m_next){ c.m_next.m_prev = c.m_prev; }; if (m_controllerList == c){ m_controllerList = c.m_next; }; m_controllerCount--; } public function Step(dt:Number, velocityIterations:int, positionIterations:int):void{ m_lock = true; var step:b2TimeStep = new b2TimeStep(); step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0){ step.inv_dt = (1 / dt); } else { step.inv_dt = 0; }; step.dtRatio = (m_inv_dt0 * dt); step.warmStarting = m_warmStarting; m_contactManager.Collide(); if (step.dt > 0){ Solve(step); }; if (((m_continuousPhysics) && ((step.dt > 0)))){ SolveTOI(step); }; DrawDebugData(); m_inv_dt0 = step.inv_dt; m_lock = false; } public function GetBodyCount():int{ return (m_bodyCount); } public function InRange(aabb:b2AABB):Boolean{ return (m_broadPhase.InRange(aabb)); } public function GetJointCount():int{ return (m_jointCount); } public function AddController(c:b2Controller):b2Controller{ c.m_next = m_controllerList; c.m_prev = null; m_controllerList = c; c.m_world = this; m_controllerCount++; return (c); } } }//package Box2D.Dynamics
Section 85
//AuxFunctions (caurina.transitions.AuxFunctions) package caurina.transitions { public class AuxFunctions { public function AuxFunctions(){ super(); } public static function getObjectLength(p_object:Object):uint{ var pName:String; var totalProperties:uint; for (pName in p_object) { totalProperties++; }; return (totalProperties); } public static function numberToG(p_num:Number):Number{ return (((p_num & 0xFF00) >> 8)); } public static function numberToB(p_num:Number):Number{ return ((p_num & 0xFF)); } public static function numberToR(p_num:Number):Number{ return (((p_num & 0xFF0000) >> 16)); } public static function concatObjects(... _args):Object{ var currentObject:Object; var prop:String; var finalObject:Object = {}; var i:int; while (i < _args.length) { currentObject = _args[i]; for (prop in currentObject) { if (currentObject[prop] == null){ delete finalObject[prop]; } else { finalObject[prop] = currentObject[prop]; }; }; i++; }; return (finalObject); } } }//package caurina.transitions
Section 86
//Equations (caurina.transitions.Equations) package caurina.transitions { public class Equations { public function Equations(){ super(); trace("Equations is a static class and should not be instantiated."); } public static function easeOutBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); if (t < (1 / 2.75)){ return (((c * ((7.5625 * t) * t)) + b)); }; if (t < (2 / 2.75)){ t = (t - (1.5 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.75)) + b)); }; if (t < (2.5 / 2.75)){ t = (t - (2.25 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.9375)) + b)); }; t = (t - (2.625 / 2.75)); return (((c * (((7.5625 * t) * t) + 0.984375)) + b)); } public static function easeInOutElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / (d / 2)); if (t == 2){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * (0.3 * 1.5)) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; if (t < 1){ --t; return (((-0.5 * ((a * Math.pow(2, (10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p)))) + b)); }; --t; return ((((((a * Math.pow(2, (-10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p))) * 0.5) + c) + b)); } public static function easeInOutQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return (((((c / 2) * t) * t) + b)); }; --t; return ((((-(c) / 2) * ((t * (t - 2)) - 1)) + b)); } public static function easeInOutBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (((easeInBounce((t * 2), 0, c, d) * 0.5) + b)); }; return ((((easeOutBounce(((t * 2) - d), 0, c, d) * 0.5) + (c * 0.5)) + b)); } public static function easeInOutBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = (t / (d / 2)); if (t < 1){ s = (s * 1.525); return ((((c / 2) * ((t * t) * (((s + 1) * t) - s))) + b)); }; t = (t - 2); s = (s * 1.525); return ((((c / 2) * (((t * t) * (((s + 1) * t) + s)) + 2)) + b)); } public static function easeOutInCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutCubic((t * 2), b, (c / 2), d, p_params)); }; return (easeInCubic(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeNone(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((c * t) / d) + b)); } public static function easeOutBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = ((t / d) - 1); return (((c * (((t * t) * (((s + 1) * t) + s)) + 1)) + b)); } public static function easeInOutSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((-(c) / 2) * (Math.cos(((Math.PI * t) / d)) - 1)) + b)); } public static function easeInBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number = (((!(Boolean(p_params))) || (isNaN(p_params.overshoot)))) ? 1.70158 : p_params.overshoot; t = (t / d); return (((((c * t) * t) * (((s + 1) * t) - s)) + b)); } public static function easeInQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((((c * t) * t) * t) * t) + b)); } public static function easeOutInQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuint((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuint(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutInBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutBounce((t * 2), b, (c / 2), d, p_params)); }; return (easeInBounce(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function init():void{ Tweener.registerTransition("easenone", easeNone); Tweener.registerTransition("linear", easeNone); Tweener.registerTransition("easeinquad", easeInQuad); Tweener.registerTransition("easeoutquad", easeOutQuad); Tweener.registerTransition("easeinoutquad", easeInOutQuad); Tweener.registerTransition("easeoutinquad", easeOutInQuad); Tweener.registerTransition("easeincubic", easeInCubic); Tweener.registerTransition("easeoutcubic", easeOutCubic); Tweener.registerTransition("easeinoutcubic", easeInOutCubic); Tweener.registerTransition("easeoutincubic", easeOutInCubic); Tweener.registerTransition("easeinquart", easeInQuart); Tweener.registerTransition("easeoutquart", easeOutQuart); Tweener.registerTransition("easeinoutquart", easeInOutQuart); Tweener.registerTransition("easeoutinquart", easeOutInQuart); Tweener.registerTransition("easeinquint", easeInQuint); Tweener.registerTransition("easeoutquint", easeOutQuint); Tweener.registerTransition("easeinoutquint", easeInOutQuint); Tweener.registerTransition("easeoutinquint", easeOutInQuint); Tweener.registerTransition("easeinsine", easeInSine); Tweener.registerTransition("easeoutsine", easeOutSine); Tweener.registerTransition("easeinoutsine", easeInOutSine); Tweener.registerTransition("easeoutinsine", easeOutInSine); Tweener.registerTransition("easeincirc", easeInCirc); Tweener.registerTransition("easeoutcirc", easeOutCirc); Tweener.registerTransition("easeinoutcirc", easeInOutCirc); Tweener.registerTransition("easeoutincirc", easeOutInCirc); Tweener.registerTransition("easeinexpo", easeInExpo); Tweener.registerTransition("easeoutexpo", easeOutExpo); Tweener.registerTransition("easeinoutexpo", easeInOutExpo); Tweener.registerTransition("easeoutinexpo", easeOutInExpo); Tweener.registerTransition("easeinelastic", easeInElastic); Tweener.registerTransition("easeoutelastic", easeOutElastic); Tweener.registerTransition("easeinoutelastic", easeInOutElastic); Tweener.registerTransition("easeoutinelastic", easeOutInElastic); Tweener.registerTransition("easeinback", easeInBack); Tweener.registerTransition("easeoutback", easeOutBack); Tweener.registerTransition("easeinoutback", easeInOutBack); Tweener.registerTransition("easeoutinback", easeOutInBack); Tweener.registerTransition("easeinbounce", easeInBounce); Tweener.registerTransition("easeoutbounce", easeOutBounce); Tweener.registerTransition("easeinoutbounce", easeInOutBounce); Tweener.registerTransition("easeoutinbounce", easeOutInBounce); } public static function easeOutExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((t)==d) ? (b + c) : (((c * 1.001) * (-(Math.pow(2, ((-10 * t) / d))) + 1)) + b)); } public static function easeOutInBack(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutBack((t * 2), b, (c / 2), d, p_params)); }; return (easeInBack(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((t)==0) ? b : (((c * Math.pow(2, (10 * ((t / d) - 1)))) + b) - (c * 0.001))); } public static function easeInCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((((c * t) * t) * t) + b)); } public static function easeInQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((((((c * t) * t) * t) * t) * t) + b)); } public static function easeInOutCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((-(c) / 2) * (Math.sqrt((1 - (t * t))) - 1)) + b)); }; t = (t - 2); return ((((c / 2) * (Math.sqrt((1 - (t * t))) + 1)) + b)); } public static function easeInQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((c * t) * t) + b)); } public static function easeInBounce(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((c - easeOutBounce((d - t), 0, c, d)) + b)); } public static function easeOutInExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutExpo((t * 2), b, (c / 2), d, p_params)); }; return (easeInExpo(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((-(c) * ((((t * t) * t) * t) - 1)) + b)); } public static function easeInSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return ((((-(c) * Math.cos(((t / d) * (Math.PI / 2)))) + c) + b)); } public static function easeInOutQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return (((((((c / 2) * t) * t) * t) * t) + b)); }; t = (t - 2); return ((((-(c) / 2) * ((((t * t) * t) * t) - 2)) + b)); } public static function easeOutQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return ((((-(c) * t) * (t - 2)) + b)); } public static function easeOutInElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutElastic((t * 2), b, (c / 2), d, p_params)); }; return (easeInElastic(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / d); if (t == 1){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * 0.3) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; --t; return ((-(((a * Math.pow(2, (10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p)))) + b)); } public static function easeOutCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * (((t * t) * t) + 1)) + b)); } public static function easeOutQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * (((((t * t) * t) * t) * t) + 1)) + b)); } public static function easeOutInQuad(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuad((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuad(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ return (((c * Math.sin(((t / d) * (Math.PI / 2)))) + b)); } public static function easeInOutCubic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((((c / 2) * t) * t) * t) + b)); }; t = (t - 2); return ((((c / 2) * (((t * t) * t) + 2)) + b)); } public static function easeInOutQuint(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / (d / 2)); if (t < 1){ return ((((((((c / 2) * t) * t) * t) * t) * t) + b)); }; t = (t - 2); return ((((c / 2) * (((((t * t) * t) * t) * t) + 2)) + b)); } public static function easeInCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = (t / d); return (((-(c) * (Math.sqrt((1 - (t * t))) - 1)) + b)); } public static function easeOutInSine(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutSine((t * 2), b, (c / 2), d, p_params)); }; return (easeInSine(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeInOutExpo(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t == 0){ return (b); }; if (t == d){ return ((b + c)); }; t = (t / (d / 2)); if (t < 1){ return (((((c / 2) * Math.pow(2, (10 * (t - 1)))) + b) - (c * 0.0005))); }; --t; return (((((c / 2) * 1.0005) * (-(Math.pow(2, (-10 * t))) + 2)) + b)); } public static function easeOutElastic(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ var s:Number; if (t == 0){ return (b); }; t = (t / d); if (t == 1){ return ((b + c)); }; var p:Number = (((!(Boolean(p_params))) || (isNaN(p_params.period)))) ? (d * 0.3) : p_params.period; var a:Number = (((!(Boolean(p_params))) || (isNaN(p_params.amplitude)))) ? 0 : p_params.amplitude; if (((!(Boolean(a))) || ((a < Math.abs(c))))){ a = c; s = (p / 4); } else { s = ((p / (2 * Math.PI)) * Math.asin((c / a))); }; return (((((a * Math.pow(2, (-10 * t))) * Math.sin(((((t * d) - s) * (2 * Math.PI)) / p))) + c) + b)); } public static function easeOutCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ t = ((t / d) - 1); return (((c * Math.sqrt((1 - (t * t)))) + b)); } public static function easeOutInQuart(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutQuart((t * 2), b, (c / 2), d, p_params)); }; return (easeInQuart(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } public static function easeOutInCirc(t:Number, b:Number, c:Number, d:Number, p_params:Object=null):Number{ if (t < (d / 2)){ return (easeOutCirc((t * 2), b, (c / 2), d, p_params)); }; return (easeInCirc(((t * 2) - d), (b + (c / 2)), (c / 2), d, p_params)); } } }//package caurina.transitions
Section 87
//PropertyInfoObj (caurina.transitions.PropertyInfoObj) package caurina.transitions { public class PropertyInfoObj { public var modifierParameters:Array; public var isSpecialProperty:Boolean; public var valueComplete:Number; public var modifierFunction:Function; public var extra:Object; public var valueStart:Number; public var hasModifier:Boolean; public var arrayIndex:Number; public var originalValueComplete:Object; public function PropertyInfoObj(p_valueStart:Number, p_valueComplete:Number, p_originalValueComplete:Object, p_arrayIndex:Number, p_extra:Object, p_isSpecialProperty:Boolean, p_modifierFunction:Function, p_modifierParameters:Array){ super(); valueStart = p_valueStart; valueComplete = p_valueComplete; originalValueComplete = p_originalValueComplete; arrayIndex = p_arrayIndex; extra = p_extra; isSpecialProperty = p_isSpecialProperty; hasModifier = Boolean(p_modifierFunction); modifierFunction = p_modifierFunction; modifierParameters = p_modifierParameters; } public function toString():String{ var returnStr:String = "\n[PropertyInfoObj "; returnStr = (returnStr + ("valueStart:" + String(valueStart))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("valueComplete:" + String(valueComplete))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("originalValueComplete:" + String(originalValueComplete))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("arrayIndex:" + String(arrayIndex))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("extra:" + String(extra))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("isSpecialProperty:" + String(isSpecialProperty))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("hasModifier:" + String(hasModifier))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("modifierFunction:" + String(modifierFunction))); returnStr = (returnStr + ", "); returnStr = (returnStr + ("modifierParameters:" + String(modifierParameters))); returnStr = (returnStr + "]\n"); return (returnStr); } public function clone():PropertyInfoObj{ var nProperty:PropertyInfoObj = new PropertyInfoObj(valueStart, valueComplete, originalValueComplete, arrayIndex, extra, isSpecialProperty, modifierFunction, modifierParameters); return (nProperty); } } }//package caurina.transitions
Section 88
//SpecialProperty (caurina.transitions.SpecialProperty) package caurina.transitions { public class SpecialProperty { public var parameters:Array; public var getValue:Function; public var preProcess:Function; public var setValue:Function; public function SpecialProperty(p_getFunction:Function, p_setFunction:Function, p_parameters:Array=null, p_preProcessFunction:Function=null){ super(); getValue = p_getFunction; setValue = p_setFunction; parameters = p_parameters; preProcess = p_preProcessFunction; } public function toString():String{ var value:String = ""; value = (value + "[SpecialProperty "); value = (value + ("getValue:" + String(getValue))); value = (value + ", "); value = (value + ("setValue:" + String(setValue))); value = (value + ", "); value = (value + ("parameters:" + String(parameters))); value = (value + ", "); value = (value + ("preProcess:" + String(preProcess))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 89
//SpecialPropertyModifier (caurina.transitions.SpecialPropertyModifier) package caurina.transitions { public class SpecialPropertyModifier { public var getValue:Function; public var modifyValues:Function; public function SpecialPropertyModifier(p_modifyFunction:Function, p_getFunction:Function){ super(); modifyValues = p_modifyFunction; getValue = p_getFunction; } public function toString():String{ var value:String = ""; value = (value + "[SpecialPropertyModifier "); value = (value + ("modifyValues:" + String(modifyValues))); value = (value + ", "); value = (value + ("getValue:" + String(getValue))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 90
//SpecialPropertySplitter (caurina.transitions.SpecialPropertySplitter) package caurina.transitions { public class SpecialPropertySplitter { public var parameters:Array; public var splitValues:Function; public function SpecialPropertySplitter(p_splitFunction:Function, p_parameters:Array){ super(); splitValues = p_splitFunction; parameters = p_parameters; } public function toString():String{ var value:String = ""; value = (value + "[SpecialPropertySplitter "); value = (value + ("splitValues:" + String(splitValues))); value = (value + ", "); value = (value + ("parameters:" + String(parameters))); value = (value + "]"); return (value); } } }//package caurina.transitions
Section 91
//Tweener (caurina.transitions.Tweener) package caurina.transitions { import flash.events.*; import flash.display.*; import flash.utils.*; public class Tweener { private static var _timeScale:Number = 1; private static var _currentTimeFrame:Number; private static var _specialPropertySplitterList:Object; private static var _engineExists:Boolean = false; private static var _specialPropertyModifierList:Object; private static var _currentTime:Number; private static var _tweenList:Array; private static var _specialPropertyList:Object; private static var _transitionList:Object; private static var _inited:Boolean = false; private static var __tweener_controller__:MovieClip; public function Tweener(){ super(); trace("Tweener is a static class and should not be instantiated."); } public static function registerSpecialPropertyModifier(p_name:String, p_modifyFunction:Function, p_getFunction:Function):void{ if (!_inited){ init(); }; var spm:SpecialPropertyModifier = new SpecialPropertyModifier(p_modifyFunction, p_getFunction); _specialPropertyModifierList[p_name] = spm; } public static function registerSpecialProperty(p_name:String, p_getFunction:Function, p_setFunction:Function, p_parameters:Array=null, p_preProcessFunction:Function=null):void{ if (!_inited){ init(); }; var sp:SpecialProperty = new SpecialProperty(p_getFunction, p_setFunction, p_parameters, p_preProcessFunction); _specialPropertyList[p_name] = sp; } public static function init(... _args):void{ _inited = true; _transitionList = new Object(); Equations.init(); _specialPropertyList = new Object(); _specialPropertyModifierList = new Object(); _specialPropertySplitterList = new Object(); } private static function updateTweens():Boolean{ var i:int; if (_tweenList.length == 0){ return (false); }; i = 0; while (i < _tweenList.length) { if ((((_tweenList[i] == undefined)) || (!(_tweenList[i].isPaused)))){ if (!updateTweenByIndex(i)){ removeTweenByIndex(i); }; if (_tweenList[i] == null){ removeTweenByIndex(i, true); i--; }; }; i++; }; return (true); } public static function addCaller(p_scopes:Object=null, p_parameters:Object=null):Boolean{ var i:Number; var rScopes:Array; var rTransition:Function; var nTween:TweenListObj; var myT:Number; var trans:String; if (!Boolean(p_scopes)){ return (false); }; if ((p_scopes is Array)){ rScopes = p_scopes.concat(); } else { rScopes = [p_scopes]; }; var p_obj:Object = p_parameters; if (!_inited){ init(); }; if (((!(_engineExists)) || (!(Boolean(__tweener_controller__))))){ startEngine(); }; var rTime:Number = (isNaN(p_obj.time)) ? 0 : p_obj.time; var rDelay:Number = (isNaN(p_obj.delay)) ? 0 : p_obj.delay; if (typeof(p_obj.transition) == "string"){ trans = p_obj.transition.toLowerCase(); rTransition = _transitionList[trans]; } else { rTransition = p_obj.transition; }; if (!Boolean(rTransition)){ rTransition = _transitionList["easeoutexpo"]; }; i = 0; while (i < rScopes.length) { if (p_obj.useFrames == true){ nTween = new TweenListObj(rScopes[i], (_currentTimeFrame + (rDelay / _timeScale)), (_currentTimeFrame + ((rDelay + rTime) / _timeScale)), true, rTransition, p_obj.transitionParams); } else { nTween = new TweenListObj(rScopes[i], (_currentTime + ((rDelay * 1000) / _timeScale)), (_currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale)), false, rTransition, p_obj.transitionParams); }; nTween.properties = null; nTween.onStart = p_obj.onStart; nTween.onUpdate = p_obj.onUpdate; nTween.onComplete = p_obj.onComplete; nTween.onOverwrite = p_obj.onOverwrite; nTween.onStartParams = p_obj.onStartParams; nTween.onUpdateParams = p_obj.onUpdateParams; nTween.onCompleteParams = p_obj.onCompleteParams; nTween.onOverwriteParams = p_obj.onOverwriteParams; nTween.onStartScope = p_obj.onStartScope; nTween.onUpdateScope = p_obj.onUpdateScope; nTween.onCompleteScope = p_obj.onCompleteScope; nTween.onOverwriteScope = p_obj.onOverwriteScope; nTween.onErrorScope = p_obj.onErrorScope; nTween.isCaller = true; nTween.count = p_obj.count; nTween.waitFrames = p_obj.waitFrames; _tweenList.push(nTween); if ((((rTime == 0)) && ((rDelay == 0)))){ myT = (_tweenList.length - 1); updateTweenByIndex(myT); removeTweenByIndex(myT); }; i++; }; return (true); } public static function pauseAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var paused:Boolean; i = 0; while (i < _tweenList.length) { pauseTweenByIndex(i); paused = true; i++; }; return (paused); } public static function removeTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var sps:SpecialPropertySplitter; var specialProps:Array; var j:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && ((properties.indexOf(_args[i]) == -1)))){ if (_specialPropertySplitterList[_args[i]]){ sps = _specialPropertySplitterList[_args[i]]; specialProps = sps.splitValues(p_scope, null); j = 0; while (j < specialProps.length) { properties.push(specialProps[j].name); j++; }; } else { properties.push(_args[i]); }; }; i++; }; return (affectTweens(removeTweenByIndex, p_scope, properties)); } public static function splitTweens(p_tween:Number, p_properties:Array):uint{ var i:uint; var pName:String; var found:Boolean; var originalTween:TweenListObj = _tweenList[p_tween]; var newTween:TweenListObj = originalTween.clone(false); i = 0; while (i < p_properties.length) { pName = p_properties[i]; if (Boolean(originalTween.properties[pName])){ originalTween.properties[pName] = undefined; delete originalTween.properties[pName]; }; i++; }; for (pName in newTween.properties) { found = false; i = 0; while (i < p_properties.length) { if (p_properties[i] == pName){ found = true; break; }; i++; }; if (!found){ newTween.properties[pName] = undefined; delete newTween.properties[pName]; }; }; _tweenList.push(newTween); return ((_tweenList.length - 1)); } public static function updateFrame():void{ _currentTimeFrame++; } public static function resumeTweenByIndex(p_tween:Number):Boolean{ var tTweening:TweenListObj = _tweenList[p_tween]; if ((((tTweening == null)) || (!(tTweening.isPaused)))){ return (false); }; var cTime:Number = getCurrentTweeningTime(tTweening); tTweening.timeStart = (tTweening.timeStart + (cTime - tTweening.timePaused)); tTweening.timeComplete = (tTweening.timeComplete + (cTime - tTweening.timePaused)); tTweening.timePaused = undefined; tTweening.isPaused = false; return (true); } public static function getVersion():String{ return ("AS3 1.31.74"); } public static function onEnterFrame(e:Event):void{ updateTime(); updateFrame(); var hasUpdated:Boolean; hasUpdated = updateTweens(); if (!hasUpdated){ stopEngine(); }; } public static function updateTime():void{ _currentTime = getTimer(); } private static function updateTweenByIndex(i:Number):Boolean{ var tTweening:TweenListObj; var mustUpdate:Boolean; var nv:Number; var t:Number; var b:Number; var c:Number; var d:Number; var pName:String; var eventScope:Object; var tScope:Object; var tProperty:Object; var pv:Number; var i = i; tTweening = _tweenList[i]; if ((((tTweening == null)) || (!(Boolean(tTweening.scope))))){ return (false); }; var isOver:Boolean; var cTime:Number = getCurrentTweeningTime(tTweening); if (cTime >= tTweening.timeStart){ tScope = tTweening.scope; if (tTweening.isCaller){ do { t = (((tTweening.timeComplete - tTweening.timeStart) / tTweening.count) * (tTweening.timesCalled + 1)); b = tTweening.timeStart; c = (tTweening.timeComplete - tTweening.timeStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, b, c, d); //unresolved if if (Boolean(tTweening.onUpdate)){ eventScope = (Boolean(tTweening.onUpdateScope)) ? tTweening.onUpdateScope : tScope; tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); continue; var _slot1 = e1; handleError(tTweening, _slot1, "onUpdate"); }; } while (tTweening.timesCalled++, !(tTweening.timesCalled >= tTweening.count)); } else { mustUpdate = (((((tTweening.skipUpdates < 1)) || (!(tTweening.skipUpdates)))) || ((tTweening.updatesSkipped >= tTweening.skipUpdates))); if (cTime >= tTweening.timeComplete){ isOver = true; mustUpdate = true; }; if (!tTweening.hasStarted){ if (Boolean(tTweening.onStart)){ eventScope = (Boolean(tTweening.onStartScope)) ? tTweening.onStartScope : tScope; tTweening.onStart.apply(eventScope, tTweening.onStartParams); //unresolved jump var _slot1 = e2; handleError(tTweening, _slot1, "onStart"); }; for (pName in tTweening.properties) { if (tTweening.properties[pName].isSpecialProperty){ if (Boolean(_specialPropertyList[pName].preProcess)){ tTweening.properties[pName].valueComplete = _specialPropertyList[pName].preProcess(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].originalValueComplete, tTweening.properties[pName].extra); }; pv = _specialPropertyList[pName].getValue(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); } else { pv = tScope[pName]; }; tTweening.properties[pName].valueStart = (isNaN(pv)) ? tTweening.properties[pName].valueComplete : pv; }; mustUpdate = true; tTweening.hasStarted = true; }; if (mustUpdate){ for (pName in tTweening.properties) { tProperty = tTweening.properties[pName]; if (isOver){ nv = tProperty.valueComplete; } else { if (tProperty.hasModifier){ t = (cTime - tTweening.timeStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, 0, 1, d, tTweening.transitionParams); nv = tProperty.modifierFunction(tProperty.valueStart, tProperty.valueComplete, nv, tProperty.modifierParameters); } else { t = (cTime - tTweening.timeStart); b = tProperty.valueStart; c = (tProperty.valueComplete - tProperty.valueStart); d = (tTweening.timeComplete - tTweening.timeStart); nv = tTweening.transition(t, b, c, d, tTweening.transitionParams); }; }; if (tTweening.rounded){ nv = Math.round(nv); }; if (tProperty.isSpecialProperty){ _specialPropertyList[pName].setValue(tScope, nv, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); } else { tScope[pName] = nv; }; }; tTweening.updatesSkipped = 0; if (Boolean(tTweening.onUpdate)){ eventScope = (Boolean(tTweening.onUpdateScope)) ? tTweening.onUpdateScope : tScope; tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); //unresolved jump var _slot1 = e3; handleError(tTweening, _slot1, "onUpdate"); }; } else { tTweening.updatesSkipped++; }; }; if (((isOver) && (Boolean(tTweening.onComplete)))){ eventScope = (Boolean(tTweening.onCompleteScope)) ? tTweening.onCompleteScope : tScope; tTweening.onComplete.apply(eventScope, tTweening.onCompleteParams); //unresolved jump var _slot1 = e4; handleError(tTweening, _slot1, "onComplete"); }; return (!(isOver)); }; return (true); } public static function setTimeScale(p_time:Number):void{ var i:Number; var cTime:Number; if (isNaN(p_time)){ p_time = 1; }; if (p_time < 1E-5){ p_time = 1E-5; }; if (p_time != _timeScale){ if (_tweenList != null){ i = 0; while (i < _tweenList.length) { cTime = getCurrentTweeningTime(_tweenList[i]); _tweenList[i].timeStart = (cTime - (((cTime - _tweenList[i].timeStart) * _timeScale) / p_time)); _tweenList[i].timeComplete = (cTime - (((cTime - _tweenList[i].timeComplete) * _timeScale) / p_time)); if (_tweenList[i].timePaused != undefined){ _tweenList[i].timePaused = (cTime - (((cTime - _tweenList[i].timePaused) * _timeScale) / p_time)); }; i++; }; }; _timeScale = p_time; }; } public static function resumeAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var resumed:Boolean; i = 0; while (i < _tweenList.length) { resumeTweenByIndex(i); resumed = true; i++; }; return (resumed); } private static function handleError(pTweening:TweenListObj, pError:Error, pCallBackName:String):void{ var eventScope:Object; var pTweening = pTweening; var pError = pError; var pCallBackName = pCallBackName; if (((Boolean(pTweening.onError)) && ((pTweening.onError is Function)))){ eventScope = (Boolean(pTweening.onErrorScope)) ? pTweening.onErrorScope : pTweening.scope; pTweening.onError.apply(eventScope, [pTweening.scope, pError]); //unresolved jump var _slot1 = metaError; printError(((((String(pTweening.scope) + " raised an error while executing the 'onError' handler. Original error:\n ") + pError.getStackTrace()) + "\nonError error: ") + _slot1.getStackTrace())); } else { if (!Boolean(pTweening.onError)){ printError(((((String(pTweening.scope) + " raised an error while executing the '") + pCallBackName) + "'handler. \n") + pError.getStackTrace())); }; }; } private static function startEngine():void{ _engineExists = true; _tweenList = new Array(); __tweener_controller__ = new MovieClip(); __tweener_controller__.addEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); _currentTimeFrame = 0; updateTime(); } public static function removeAllTweens():Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; var removed:Boolean; i = 0; while (i < _tweenList.length) { removeTweenByIndex(i); removed = true; i++; }; return (removed); } public static function addTween(p_scopes:Object=null, p_parameters:Object=null):Boolean{ var i:Number; var j:Number; var istr:String; var rScopes:Array; var rTransition:Function; var nProperties:Object; var nTween:TweenListObj; var myT:Number; var splitProperties:Array; var splitProperties2:Array; var tempModifiedProperties:Array; var trans:String; if (!Boolean(p_scopes)){ return (false); }; if ((p_scopes is Array)){ rScopes = p_scopes.concat(); } else { rScopes = [p_scopes]; }; var p_obj:Object = TweenListObj.makePropertiesChain(p_parameters); if (!_inited){ init(); }; if (((!(_engineExists)) || (!(Boolean(__tweener_controller__))))){ startEngine(); }; var rTime:Number = (isNaN(p_obj.time)) ? 0 : p_obj.time; var rDelay:Number = (isNaN(p_obj.delay)) ? 0 : p_obj.delay; var rProperties:Array = new Array(); var restrictedWords:Object = {time:true, delay:true, useFrames:true, skipUpdates:true, transition:true, transitionParams:true, onStart:true, onUpdate:true, onComplete:true, onOverwrite:true, onError:true, rounded:true, onStartParams:true, onUpdateParams:true, onCompleteParams:true, onOverwriteParams:true, onStartScope:true, onUpdateScope:true, onCompleteScope:true, onOverwriteScope:true, onErrorScope:true}; var modifiedProperties:Object = new Object(); for (istr in p_obj) { if (!restrictedWords[istr]){ if (_specialPropertySplitterList[istr]){ splitProperties = _specialPropertySplitterList[istr].splitValues(p_obj[istr], _specialPropertySplitterList[istr].parameters); i = 0; while (i < splitProperties.length) { if (_specialPropertySplitterList[splitProperties[i].name]){ splitProperties2 = _specialPropertySplitterList[splitProperties[i].name].splitValues(splitProperties[i].value, _specialPropertySplitterList[splitProperties[i].name].parameters); j = 0; while (j < splitProperties2.length) { rProperties[splitProperties2[j].name] = {valueStart:undefined, valueComplete:splitProperties2[j].value, arrayIndex:splitProperties2[j].arrayIndex, isSpecialProperty:false}; j++; }; } else { rProperties[splitProperties[i].name] = {valueStart:undefined, valueComplete:splitProperties[i].value, arrayIndex:splitProperties[i].arrayIndex, isSpecialProperty:false}; }; i++; }; } else { if (_specialPropertyModifierList[istr] != undefined){ tempModifiedProperties = _specialPropertyModifierList[istr].modifyValues(p_obj[istr]); i = 0; while (i < tempModifiedProperties.length) { modifiedProperties[tempModifiedProperties[i].name] = {modifierParameters:tempModifiedProperties[i].parameters, modifierFunction:_specialPropertyModifierList[istr].getValue}; i++; }; } else { rProperties[istr] = {valueStart:undefined, valueComplete:p_obj[istr]}; }; }; }; }; for (istr in rProperties) { if (_specialPropertyList[istr] != undefined){ rProperties[istr].isSpecialProperty = true; } else { if (rScopes[0][istr] == undefined){ printError((((("The property '" + istr) + "' doesn't seem to be a normal object property of ") + String(rScopes[0])) + " or a registered special property.")); }; }; }; for (istr in modifiedProperties) { if (rProperties[istr] != undefined){ rProperties[istr].modifierParameters = modifiedProperties[istr].modifierParameters; rProperties[istr].modifierFunction = modifiedProperties[istr].modifierFunction; }; }; if (typeof(p_obj.transition) == "string"){ trans = p_obj.transition.toLowerCase(); rTransition = _transitionList[trans]; } else { rTransition = p_obj.transition; }; if (!Boolean(rTransition)){ rTransition = _transitionList["easeoutexpo"]; }; i = 0; while (i < rScopes.length) { nProperties = new Object(); for (istr in rProperties) { nProperties[istr] = new PropertyInfoObj(rProperties[istr].valueStart, rProperties[istr].valueComplete, rProperties[istr].valueComplete, rProperties[istr].arrayIndex, {}, rProperties[istr].isSpecialProperty, rProperties[istr].modifierFunction, rProperties[istr].modifierParameters); }; if (p_obj.useFrames == true){ nTween = new TweenListObj(rScopes[i], (_currentTimeFrame + (rDelay / _timeScale)), (_currentTimeFrame + ((rDelay + rTime) / _timeScale)), true, rTransition, p_obj.transitionParams); } else { nTween = new TweenListObj(rScopes[i], (_currentTime + ((rDelay * 1000) / _timeScale)), (_currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale)), false, rTransition, p_obj.transitionParams); }; nTween.properties = nProperties; nTween.onStart = p_obj.onStart; nTween.onUpdate = p_obj.onUpdate; nTween.onComplete = p_obj.onComplete; nTween.onOverwrite = p_obj.onOverwrite; nTween.onError = p_obj.onError; nTween.onStartParams = p_obj.onStartParams; nTween.onUpdateParams = p_obj.onUpdateParams; nTween.onCompleteParams = p_obj.onCompleteParams; nTween.onOverwriteParams = p_obj.onOverwriteParams; nTween.onStartScope = p_obj.onStartScope; nTween.onUpdateScope = p_obj.onUpdateScope; nTween.onCompleteScope = p_obj.onCompleteScope; nTween.onOverwriteScope = p_obj.onOverwriteScope; nTween.onErrorScope = p_obj.onErrorScope; nTween.rounded = p_obj.rounded; nTween.skipUpdates = p_obj.skipUpdates; removeTweensByTime(nTween.scope, nTween.properties, nTween.timeStart, nTween.timeComplete); _tweenList.push(nTween); if ((((rTime == 0)) && ((rDelay == 0)))){ myT = (_tweenList.length - 1); updateTweenByIndex(myT); removeTweenByIndex(myT); }; i++; }; return (true); } public static function registerTransition(p_name:String, p_function:Function):void{ if (!_inited){ init(); }; _transitionList[p_name] = p_function; } public static function printError(p_message:String):void{ trace(("## [Tweener] Error: " + p_message)); } private static function affectTweens(p_affectFunction:Function, p_scope:Object, p_properties:Array):Boolean{ var i:uint; var affectedProperties:Array; var j:uint; var objectProperties:uint; var slicedTweenIndex:uint; var affected:Boolean; if (!Boolean(_tweenList)){ return (false); }; i = 0; while (i < _tweenList.length) { if (((_tweenList[i]) && ((_tweenList[i].scope == p_scope)))){ if (p_properties.length == 0){ p_affectFunction(i); affected = true; } else { affectedProperties = new Array(); j = 0; while (j < p_properties.length) { if (Boolean(_tweenList[i].properties[p_properties[j]])){ affectedProperties.push(p_properties[j]); }; j++; }; if (affectedProperties.length > 0){ objectProperties = AuxFunctions.getObjectLength(_tweenList[i].properties); if (objectProperties == affectedProperties.length){ p_affectFunction(i); affected = true; } else { slicedTweenIndex = splitTweens(i, affectedProperties); p_affectFunction(slicedTweenIndex); affected = true; }; }; }; }; i++; }; return (affected); } public static function getTweens(p_scope:Object):Array{ var i:uint; var pName:String; if (!Boolean(_tweenList)){ return ([]); }; var tList:Array = new Array(); i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ for (pName in _tweenList[i].properties) { tList.push(pName); }; }; i++; }; return (tList); } public static function isTweening(p_scope:Object):Boolean{ var i:uint; if (!Boolean(_tweenList)){ return (false); }; i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ return (true); }; i++; }; return (false); } public static function pauseTweenByIndex(p_tween:Number):Boolean{ var tTweening:TweenListObj = _tweenList[p_tween]; if ((((tTweening == null)) || (tTweening.isPaused))){ return (false); }; tTweening.timePaused = getCurrentTweeningTime(tTweening); tTweening.isPaused = true; return (true); } public static function getCurrentTweeningTime(p_tweening:Object):Number{ return ((p_tweening.useFrames) ? _currentTimeFrame : _currentTime); } public static function getTweenCount(p_scope:Object):Number{ var i:uint; if (!Boolean(_tweenList)){ return (0); }; var c:Number = 0; i = 0; while (i < _tweenList.length) { if (((Boolean(_tweenList[i])) && ((_tweenList[i].scope == p_scope)))){ c = (c + AuxFunctions.getObjectLength(_tweenList[i].properties)); }; i++; }; return (c); } private static function stopEngine():void{ _engineExists = false; _tweenList = null; _currentTime = 0; _currentTimeFrame = 0; __tweener_controller__.removeEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); __tweener_controller__ = null; } public static function removeTweensByTime(p_scope:Object, p_properties:Object, p_timeStart:Number, p_timeComplete:Number):Boolean{ var removedLocally:Boolean; var i:uint; var pName:String; var eventScope:Object; var p_scope = p_scope; var p_properties = p_properties; var p_timeStart = p_timeStart; var p_timeComplete = p_timeComplete; var removed:Boolean; var tl:uint = _tweenList.length; i = 0; while (i < tl) { if (((Boolean(_tweenList[i])) && ((p_scope == _tweenList[i].scope)))){ if ((((p_timeComplete > _tweenList[i].timeStart)) && ((p_timeStart < _tweenList[i].timeComplete)))){ removedLocally = false; for (pName in _tweenList[i].properties) { if (Boolean(p_properties[pName])){ if (Boolean(_tweenList[i].onOverwrite)){ eventScope = (Boolean(_tweenList[i].onOverwriteScope)) ? _tweenList[i].onOverwriteScope : _tweenList[i].scope; _tweenList[i].onOverwrite.apply(eventScope, _tweenList[i].onOverwriteParams); //unresolved jump var _slot1 = e; handleError(_tweenList[i], _slot1, "onOverwrite"); }; _tweenList[i].properties[pName] = undefined; delete _tweenList[i].properties[pName]; removedLocally = true; removed = true; }; }; if (removedLocally){ if (AuxFunctions.getObjectLength(_tweenList[i].properties) == 0){ removeTweenByIndex(i); }; }; }; }; i = (i + 1); }; return (removed); } public static function registerSpecialPropertySplitter(p_name:String, p_splitFunction:Function, p_parameters:Array=null):void{ if (!_inited){ init(); }; var sps:SpecialPropertySplitter = new SpecialPropertySplitter(p_splitFunction, p_parameters); _specialPropertySplitterList[p_name] = sps; } public static function removeTweenByIndex(i:Number, p_finalRemoval:Boolean=false):Boolean{ _tweenList[i] = null; if (p_finalRemoval){ _tweenList.splice(i, 1); }; return (true); } public static function resumeTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && ((properties.indexOf(_args[i]) == -1)))){ properties.push(_args[i]); }; i++; }; return (affectTweens(resumeTweenByIndex, p_scope, properties)); } public static function pauseTweens(p_scope:Object, ... _args):Boolean{ var i:uint; var properties:Array = new Array(); i = 0; while (i < _args.length) { if ((((typeof(_args[i]) == "string")) && ((properties.indexOf(_args[i]) == -1)))){ properties.push(_args[i]); }; i++; }; return (affectTweens(pauseTweenByIndex, p_scope, properties)); } } }//package caurina.transitions
Section 92
//TweenListObj (caurina.transitions.TweenListObj) package caurina.transitions { public class TweenListObj { public var hasStarted:Boolean; public var onUpdate:Function; public var useFrames:Boolean; public var count:Number; public var onOverwriteParams:Array; public var timeStart:Number; public var timeComplete:Number; public var onStartParams:Array; public var onUpdateScope:Object; public var rounded:Boolean; public var onUpdateParams:Array; public var properties:Object; public var onComplete:Function; public var transitionParams:Object; public var updatesSkipped:Number; public var onStart:Function; public var onOverwriteScope:Object; public var skipUpdates:Number; public var onStartScope:Object; public var scope:Object; public var isCaller:Boolean; public var timePaused:Number; public var transition:Function; public var onCompleteParams:Array; public var onError:Function; public var timesCalled:Number; public var onErrorScope:Object; public var onOverwrite:Function; public var isPaused:Boolean; public var waitFrames:Boolean; public var onCompleteScope:Object; public function TweenListObj(p_scope:Object, p_timeStart:Number, p_timeComplete:Number, p_useFrames:Boolean, p_transition:Function, p_transitionParams:Object){ super(); scope = p_scope; timeStart = p_timeStart; timeComplete = p_timeComplete; useFrames = p_useFrames; transition = p_transition; transitionParams = p_transitionParams; properties = new Object(); isPaused = false; timePaused = undefined; isCaller = false; updatesSkipped = 0; timesCalled = 0; skipUpdates = 0; hasStarted = false; } public function clone(omitEvents:Boolean):TweenListObj{ var pName:String; var nTween:TweenListObj = new TweenListObj(scope, timeStart, timeComplete, useFrames, transition, transitionParams); nTween.properties = new Array(); for (pName in properties) { nTween.properties[pName] = properties[pName].clone(); }; nTween.skipUpdates = skipUpdates; nTween.updatesSkipped = updatesSkipped; if (!omitEvents){ nTween.onStart = onStart; nTween.onUpdate = onUpdate; nTween.onComplete = onComplete; nTween.onOverwrite = onOverwrite; nTween.onError = onError; nTween.onStartParams = onStartParams; nTween.onUpdateParams = onUpdateParams; nTween.onCompleteParams = onCompleteParams; nTween.onOverwriteParams = onOverwriteParams; nTween.onStartScope = onStartScope; nTween.onUpdateScope = onUpdateScope; nTween.onCompleteScope = onCompleteScope; nTween.onOverwriteScope = onOverwriteScope; nTween.onErrorScope = onErrorScope; }; nTween.rounded = rounded; nTween.isPaused = isPaused; nTween.timePaused = timePaused; nTween.isCaller = isCaller; nTween.count = count; nTween.timesCalled = timesCalled; nTween.waitFrames = waitFrames; nTween.hasStarted = hasStarted; return (nTween); } public function toString():String{ var i:String; var returnStr:String = "\n[TweenListObj "; returnStr = (returnStr + ("scope:" + String(scope))); returnStr = (returnStr + ", properties:"); var isFirst:Boolean; for (i in properties) { if (!isFirst){ returnStr = (returnStr + ","); }; returnStr = (returnStr + ("[name:" + properties[i].name)); returnStr = (returnStr + (",valueStart:" + properties[i].valueStart)); returnStr = (returnStr + (",valueComplete:" + properties[i].valueComplete)); returnStr = (returnStr + "]"); isFirst = false; }; returnStr = (returnStr + (", timeStart:" + String(timeStart))); returnStr = (returnStr + (", timeComplete:" + String(timeComplete))); returnStr = (returnStr + (", useFrames:" + String(useFrames))); returnStr = (returnStr + (", transition:" + String(transition))); returnStr = (returnStr + (", transitionParams:" + String(transitionParams))); if (skipUpdates){ returnStr = (returnStr + (", skipUpdates:" + String(skipUpdates))); }; if (updatesSkipped){ returnStr = (returnStr + (", updatesSkipped:" + String(updatesSkipped))); }; if (Boolean(onStart)){ returnStr = (returnStr + (", onStart:" + String(onStart))); }; if (Boolean(onUpdate)){ returnStr = (returnStr + (", onUpdate:" + String(onUpdate))); }; if (Boolean(onComplete)){ returnStr = (returnStr + (", onComplete:" + String(onComplete))); }; if (Boolean(onOverwrite)){ returnStr = (returnStr + (", onOverwrite:" + String(onOverwrite))); }; if (Boolean(onError)){ returnStr = (returnStr + (", onError:" + String(onError))); }; if (onStartParams){ returnStr = (returnStr + (", onStartParams:" + String(onStartParams))); }; if (onUpdateParams){ returnStr = (returnStr + (", onUpdateParams:" + String(onUpdateParams))); }; if (onCompleteParams){ returnStr = (returnStr + (", onCompleteParams:" + String(onCompleteParams))); }; if (onOverwriteParams){ returnStr = (returnStr + (", onOverwriteParams:" + String(onOverwriteParams))); }; if (onStartScope){ returnStr = (returnStr + (", onStartScope:" + String(onStartScope))); }; if (onUpdateScope){ returnStr = (returnStr + (", onUpdateScope:" + String(onUpdateScope))); }; if (onCompleteScope){ returnStr = (returnStr + (", onCompleteScope:" + String(onCompleteScope))); }; if (onOverwriteScope){ returnStr = (returnStr + (", onOverwriteScope:" + String(onOverwriteScope))); }; if (onErrorScope){ returnStr = (returnStr + (", onErrorScope:" + String(onErrorScope))); }; if (rounded){ returnStr = (returnStr + (", rounded:" + String(rounded))); }; if (isPaused){ returnStr = (returnStr + (", isPaused:" + String(isPaused))); }; if (timePaused){ returnStr = (returnStr + (", timePaused:" + String(timePaused))); }; if (isCaller){ returnStr = (returnStr + (", isCaller:" + String(isCaller))); }; if (count){ returnStr = (returnStr + (", count:" + String(count))); }; if (timesCalled){ returnStr = (returnStr + (", timesCalled:" + String(timesCalled))); }; if (waitFrames){ returnStr = (returnStr + (", waitFrames:" + String(waitFrames))); }; if (hasStarted){ returnStr = (returnStr + (", hasStarted:" + String(hasStarted))); }; returnStr = (returnStr + "]\n"); return (returnStr); } public static function makePropertiesChain(p_obj:Object):Object{ var chainedObject:Object; var chain:Object; var currChainObj:Object; var len:Number; var i:Number; var k:Number; var baseObject:Object = p_obj.base; if (baseObject){ chainedObject = {}; if ((baseObject is Array)){ chain = []; k = 0; while (k < baseObject.length) { chain.push(baseObject[k]); k++; }; } else { chain = [baseObject]; }; chain.push(p_obj); len = chain.length; i = 0; while (i < len) { if (chain[i]["base"]){ currChainObj = AuxFunctions.concatObjects(makePropertiesChain(chain[i]["base"]), chain[i]); } else { currChainObj = chain[i]; }; chainedObject = AuxFunctions.concatObjects(chainedObject, currChainObj); i++; }; if (chainedObject["base"]){ delete chainedObject["base"]; }; return (chainedObject); //unresolved jump }; return (p_obj); } } }//package caurina.transitions
Section 93
//SoundSystem (com.urbansquall.audio.SoundSystem) package com.urbansquall.audio { import flash.events.*; import flash.media.*; import flash.utils.*; public class SoundSystem { private var m_loopMap:Dictionary; private var m_isMuted:Boolean; private var m_effectMasterVolumeModifier:Number;// = 0.75 private var m_loopMasterVolumeModifier:Number;// = 0.75 private var m_volume:Number; private static var s_singleton:SoundSystem = null; public function SoundSystem(){ super(); m_loopMap = new Dictionary(); m_isMuted = false; m_volume = 1; } public function createLoop(a_id:String, a_sound:Sound, a_volume:Number=1, a_startImmediately:Boolean=true, a_ignoreMute:Boolean=false):Boolean{ if (((!((m_loopMap[a_id] == null))) || ((a_sound == null)))){ return (false); }; var loop:BackgroundLoop = new BackgroundLoop(); loop.id = a_id; loop.customVolume = a_volume; var soundTransform:SoundTransform = new SoundTransform(); if (a_ignoreMute){ soundTransform.volume = a_volume; } else { soundTransform.volume = (a_volume * m_loopMasterVolumeModifier); }; loop.sound = a_sound; m_loopMap[a_id] = loop; if (a_startImmediately){ loop.loopChannel = a_sound.play(0, 999999999, soundTransform); }; return (true); } private function updateMute():void{ if (m_isMuted){ changeVolume(0); } else { changeVolume(m_volume); }; } public function getMasterEffectVolume():Number{ return (m_effectMasterVolumeModifier); } public function playSound(a_sound:Sound, a_volume:Number=1, a_onCompleteCallback:Function=null):SoundChannel{ var soundTransform:SoundTransform = new SoundTransform(); soundTransform.volume = (a_volume * m_effectMasterVolumeModifier); var channel:SoundChannel = a_sound.play(0, 1, soundTransform); if (a_onCompleteCallback != null){ channel.addEventListener(Event.SOUND_COMPLETE, a_onCompleteCallback); }; return (channel); } public function toggleMute():void{ m_isMuted = !(m_isMuted); updateMute(); } public function stopLoop(a_id:String):Boolean{ var loop:BackgroundLoop = m_loopMap[a_id]; if (loop != null){ if (loop.loopChannel != null){ loop.loopChannel.stop(); loop.loopChannel = null; }; return (true); }; return (false); } public function getMasterLoopVolume():Number{ return (m_loopMasterVolumeModifier); } public function mute():void{ m_isMuted = true; updateMute(); } public function setMaxVolume(a_volume:Number):void{ m_volume = a_volume; } public function isMuted():Boolean{ return (m_isMuted); } public function setMasterLoopVolume(a_volume:Number):void{ var bgLoop:BackgroundLoop; var channel:SoundChannel; var newVolume:Number; a_volume = (Math.floor((a_volume * 100)) / 100); for each (bgLoop in m_loopMap) { channel = bgLoop.loopChannel; newVolume = (bgLoop.customVolume * a_volume); if (newVolume > 1){ newVolume = 1; }; if (newVolume < 0){ newVolume = 0; }; if (channel != null){ channel.soundTransform = new SoundTransform(newVolume); }; }; m_loopMasterVolumeModifier = a_volume; } public function isPlaying(a_id:String):Boolean{ var loop:BackgroundLoop = m_loopMap[a_id]; if (loop != null){ if (loop.loopChannel != null){ if (loop.loopChannel.position > 0){ return (true); }; }; }; return (false); } public function startLoop(a_id:String, a_volume:Number=1):Boolean{ var soundTransform:SoundTransform; var loop:BackgroundLoop = m_loopMap[a_id]; if (loop != null){ if (isPlaying(a_id)){ return (false); }; soundTransform = new SoundTransform(); soundTransform.volume = (a_volume * m_loopMasterVolumeModifier); loop.loopChannel = loop.sound.play(0, 999999999, soundTransform); return (true); }; return (false); } public function setMasterEffectVolume(a_volume:Number):void{ a_volume = (Math.floor((a_volume * 100)) / 100); if (a_volume > 1){ a_volume = 1; }; if (a_volume < 0){ a_volume = 0; }; m_effectMasterVolumeModifier = a_volume; } public function changeVolume(a_volume:Number):void{ var soundTransform:SoundTransform = new SoundTransform(); soundTransform.volume = a_volume; SoundMixer.soundTransform = soundTransform; } public function changeLoopVolume(a_id:String, a_volume:Number):Boolean{ var soundTransform:SoundTransform; var loop:BackgroundLoop = m_loopMap[a_id]; if (loop == null){ return (false); }; loop.customVolume = a_volume; if (loop.loopChannel != null){ soundTransform = new SoundTransform((a_volume * m_loopMasterVolumeModifier)); loop.loopChannel.soundTransform = soundTransform; }; return (true); } public function unmute():void{ m_isMuted = false; updateMute(); } public function createSound(a_className:String):Sound{ var SoundClass:Class; var a_className = a_className; SoundClass = (getDefinitionByName(a_className) as Class); //unresolved jump var _slot1 = e; return (null); return (new (SoundClass)); } public function destroyLoop(a_id:String):Boolean{ var loop:BackgroundLoop = m_loopMap[a_id]; if (loop != null){ if (loop.loopChannel != null){ loop.loopChannel.stop(); loop.loopChannel = null; }; loop.sound = null; loop = null; delete m_loopMap[a_id]; return (true); }; return (false); } public static function get instance():SoundSystem{ if (s_singleton == null){ s_singleton = new (SoundSystem); }; return (s_singleton); } } }//package com.urbansquall.audio import flash.media.*; class BackgroundLoop { public var customVolume:Number; public var sound:Sound; public var id:String; public var loopChannel:SoundChannel; private function BackgroundLoop(){ super(); } }
Section 94
//Tile9 (com.urbansquall.display.Tile9) package com.urbansquall.display { import flash.display.*; public class Tile9 extends Sprite { var m_tile9Data:Tile9Data; var m_middleLeft:TiledSection; var m_topRight:Bitmap; var m_bottomRight:Bitmap; var m_middleMiddle:TiledSection; var m_bottomLeft:Bitmap; var m_topLeft:Bitmap; var m_bottomMiddle:TiledSection; var m_middleRight:TiledSection; var m_topMiddle:TiledSection; public function Tile9(a_tile9Data:Tile9Data){ super(); m_tile9Data = a_tile9Data; m_topLeft = new Bitmap(m_tile9Data.m_topLeft); m_topMiddle = new TiledSection(m_tile9Data.m_topMiddle); m_topRight = new Bitmap(m_tile9Data.m_topRight); m_middleLeft = new TiledSection(m_tile9Data.m_middleLeft); m_middleMiddle = new TiledSection(m_tile9Data.m_middleMiddle); m_middleRight = new TiledSection(m_tile9Data.m_middleRight); m_bottomLeft = new Bitmap(m_tile9Data.m_bottomLeft); m_bottomMiddle = new TiledSection(m_tile9Data.m_bottomMiddle); m_bottomRight = new Bitmap(m_tile9Data.m_bottomRight); m_topLeft.smoothing = false; m_topRight.smoothing = false; m_bottomLeft.smoothing = false; m_bottomRight.smoothing = false; m_topLeft.pixelSnapping = PixelSnapping.ALWAYS; m_topRight.pixelSnapping = PixelSnapping.ALWAYS; m_bottomLeft.pixelSnapping = PixelSnapping.ALWAYS; m_bottomRight.pixelSnapping = PixelSnapping.ALWAYS; addChild(m_topMiddle); addChild(m_middleLeft); addChild(m_middleMiddle); addChild(m_middleRight); addChild(m_bottomMiddle); addChild(m_topLeft); addChild(m_topRight); addChild(m_bottomLeft); addChild(m_bottomRight); reset(); } override public function set width(a_width:Number):void{ var middleWidth:Number = Math.ceil(((a_width - m_topLeft.width) - m_topRight.width)); m_topMiddle.setSize(middleWidth, m_topLeft.height); m_middleMiddle.setSize(middleWidth, m_middleMiddle.height); m_bottomMiddle.setSize(middleWidth, m_bottomLeft.height); m_topLeft.x = 0; m_topMiddle.x = m_tile9Data.m_tile9Rect.x; m_topRight.x = (a_width - m_topRight.width); m_middleLeft.x = 0; m_middleMiddle.x = m_topLeft.width; m_middleRight.x = (m_topLeft.width + m_topMiddle.width); m_bottomLeft.x = 0; m_bottomMiddle.x = m_topLeft.width; m_bottomRight.x = (a_width - m_bottomRight.width); } public function reset():void{ resize(((m_topLeft.width + m_topMiddle.width) + m_topRight.width), ((m_topLeft.height + m_middleLeft.height) + m_bottomLeft.height)); } override public function set height(a_height:Number):void{ var middleHeight:Number = Math.ceil(((a_height - m_topLeft.height) - m_bottomLeft.height)); m_topMiddle.setSize(m_topMiddle.width, m_topLeft.height); m_middleMiddle.setSize(m_middleMiddle.width, middleHeight); m_bottomMiddle.setSize(m_bottomMiddle.width, m_bottomLeft.height); m_middleLeft.setSize(m_topLeft.width, middleHeight); m_middleRight.setSize(m_topRight.width, middleHeight); m_topLeft.y = 0; m_topMiddle.y = 0; m_topRight.y = 0; m_middleLeft.y = m_topLeft.height; m_middleMiddle.y = m_topLeft.height; m_middleRight.y = m_topLeft.height; m_bottomLeft.y = (a_height - m_bottomLeft.height); m_bottomMiddle.y = (a_height - m_bottomLeft.height); m_bottomRight.y = (a_height - m_bottomLeft.height); } public function resize(a_width:Number, a_height:Number):void{ width = a_width; height = a_height; } } }//package com.urbansquall.display import flash.display.*; import flash.geom.*; class TiledSection extends Sprite { private var m_desiredWidth:Number; private var m_desiredHeight:Number; private var m_tileWrapper:Sprite; private var m_tileBitmapData:BitmapData; private function TiledSection(a_tileBitmapData:BitmapData){ super(); m_tileBitmapData = a_tileBitmapData; m_desiredWidth = a_tileBitmapData.width; m_desiredHeight = a_tileBitmapData.height; m_tileWrapper = new Sprite(); m_tileWrapper.cacheAsBitmap = true; this.addChild(m_tileWrapper); } public function setSize(a_width:Number, a_height:Number):void{ m_desiredWidth = a_width; m_desiredHeight = a_height; draw(a_width, a_height); } private function draw(a_width:Number, a_height:Number):void{ m_tileWrapper.scrollRect = new Rectangle(0, 0, m_desiredWidth, m_desiredHeight); m_tileWrapper.graphics.beginBitmapFill(m_tileBitmapData); m_tileWrapper.graphics.drawRect(0, 0, m_desiredWidth, m_desiredHeight); m_tileWrapper.graphics.endFill(); } override public function get height():Number{ return (m_desiredHeight); } override public function get width():Number{ return (m_desiredWidth); } }
Section 95
//Tile9Data (com.urbansquall.display.Tile9Data) package com.urbansquall.display { import flash.display.*; import flash.geom.*; public class Tile9Data { var m_bottomMiddle:BitmapData; var m_bottomLeft:BitmapData; var m_bottomRight:BitmapData; var m_middleLeft:BitmapData; var m_topLeft:BitmapData; var m_middleRight:BitmapData; var m_topMiddle:BitmapData; var m_topRight:BitmapData; var m_middleMiddle:BitmapData; var m_tile9Rect:Rectangle; public function Tile9Data(a_source:DisplayObject, a_tile9Rect:Rectangle){ super(); m_tile9Rect = a_tile9Rect; var bounds:Rectangle = a_source.getBounds(a_source); var left:Number = m_tile9Rect.left; var right:Number = m_tile9Rect.right; var top:Number = m_tile9Rect.top; var bottom:Number = m_tile9Rect.bottom; m_topLeft = new BitmapData(left, top, true, 0); m_topMiddle = new BitmapData(m_tile9Rect.width, top, true, 0); m_topRight = new BitmapData((bounds.width - right), top, true, 0); m_middleLeft = new BitmapData(left, m_tile9Rect.height, true, 0); m_middleMiddle = new BitmapData(m_tile9Rect.width, m_tile9Rect.height, true, 0); m_middleRight = new BitmapData((bounds.width - right), m_tile9Rect.height, true, 0); m_bottomLeft = new BitmapData(left, (bounds.height - bottom), true, 0); m_bottomMiddle = new BitmapData(m_tile9Rect.width, (bounds.height - bottom), true, 0); m_bottomRight = new BitmapData((bounds.width - right), (bounds.height - bottom), true, 0); carvePiece(m_topLeft, 0, 0, a_source); carvePiece(m_topMiddle, left, 0, a_source); carvePiece(m_topRight, right, 0, a_source); carvePiece(m_middleLeft, 0, top, a_source); carvePiece(m_middleMiddle, left, top, a_source); carvePiece(m_middleRight, right, top, a_source); carvePiece(m_bottomLeft, 0, bottom, a_source); carvePiece(m_bottomMiddle, left, bottom, a_source); carvePiece(m_bottomRight, right, bottom, a_source); } private function carvePiece(a_piece:BitmapData, a_x:Number, a_y:Number, a_source:DisplayObject):void{ var bounds:Rectangle = a_source.getBounds(a_source); var matrix:Matrix = new Matrix(); matrix.translate(-(bounds.x), -(bounds.y)); matrix.translate(-(a_x), -(a_y)); a_piece.draw(a_source, matrix, null, null, new Rectangle(0, 0, a_piece.width, a_piece.height)); } public function dispose():void{ m_topLeft.dispose(); m_topMiddle.dispose(); m_topRight.dispose(); m_middleLeft.dispose(); m_middleMiddle.dispose(); m_middleRight.dispose(); m_bottomLeft.dispose(); m_bottomMiddle.dispose(); m_bottomRight.dispose(); m_topLeft = null; m_topMiddle = null; m_topRight = null; m_middleLeft = null; m_middleMiddle = null; m_middleRight = null; m_bottomLeft = null; m_bottomMiddle = null; m_bottomRight = null; } } }//package com.urbansquall.display
Section 96
//TileSet (com.urbansquall.display.TileSet) package com.urbansquall.display { import flash.display.*; import flash.geom.*; import flash.utils.*; public class TileSet { private var m_tileWidth:int; private var m_tileHeight:int; private var m_namedIndex:int; private var m_tileDictionary:Dictionary; private var m_setName:String; public function TileSet(a_setName:String, a_tileWidth:int, a_tileHeight:int, a_bitmapData:BitmapData){ super(); m_setName = a_setName; m_tileDictionary = new Dictionary(); m_namedIndex = 0; m_tileWidth = a_tileWidth; m_tileHeight = a_tileHeight; createSlices(a_bitmapData); } public function skipNextTile():void{ m_namedIndex++; } public function lookupTileBitmapData(a_tileName:String):BitmapData{ if (m_tileDictionary[a_tileName] == null){ throw (new Error((("No tile with name [" + a_tileName) + "]"))); }; return (m_tileDictionary[a_tileName]); } public function get setName():String{ return (m_setName); } public function assignNameToNextTile(a_tileName:String):void{ if (m_tileDictionary[a_tileName] != null){ throw (new Error((("Already a tile with name [" + a_tileName) + "]"))); }; var bitmapData:BitmapData = m_tileDictionary[("__unnamed" + m_namedIndex)]; m_tileDictionary[a_tileName] = bitmapData; delete m_tileDictionary[("__unnamed" + m_namedIndex)]; m_namedIndex++; } private function createSlices(a_bitmapData:BitmapData):void{ var c:int; var slice:BitmapData; var clip:Rectangle; var matrix:Matrix; var cols:int = Math.floor((a_bitmapData.width / m_tileWidth)); var rows:int = Math.floor((a_bitmapData.height / m_tileHeight)); var index:int; var r:int; while (r < rows) { c = 0; while (c < cols) { slice = new BitmapData(m_tileWidth, m_tileHeight, true, 0); clip = new Rectangle(0, 0, m_tileWidth, m_tileHeight); matrix = new Matrix(); matrix.translate((-(c) * m_tileWidth), (-(r) * m_tileHeight)); slice.draw(a_bitmapData, matrix, null, null, clip); m_tileDictionary[("__unnamed" + index)] = slice; index++; c++; }; r++; }; } } }//package com.urbansquall.display
Section 97
//Animation (com.urbansquall.ginger.Animation) package com.urbansquall.ginger { import flash.events.*; import flash.display.*; import flash.geom.*; import flash.utils.*; public class Animation extends EventDispatcher { var m_frameMap:Dictionary; private var m_totalFrames:int; private var m_isLooping:Boolean; var m_framesOfRotation:int; var m_fps:int; var m_frames:Array; var m_degToRotBy:Number; public function Animation(a_fps:int, a_numRotations:int=1){ super(); m_frames = []; m_frameMap = new Dictionary(); m_fps = a_fps; m_isLooping = false; m_framesOfRotation = a_numRotations; if (m_framesOfRotation < 1){ m_framesOfRotation = 1; }; m_degToRotBy = (360 / m_framesOfRotation); } public function reverseFrames():void{ m_frames.reverse(); } public function changeFrameID(a_frameIndex:int, a_id:String):void{ var frame:Frame = m_frames[a_frameIndex]; frame.changeID(a_id); } public function addFrame(a_numFrames:int, a_bitmapData:BitmapData, a_frameLocation:Rectangle, a_offsetX:Number=0, a_offsetY:Number=0, a_frameID:String=null):BitmapData{ if (a_frameID == ""){ a_frameID = null; }; var bmpData:BitmapData = new BitmapData(a_frameLocation.width, a_frameLocation.height, true, 0); bmpData.copyPixels(a_bitmapData, a_frameLocation, new Point()); m_frames.push(new Frame(a_numFrames, bmpData, m_framesOfRotation, a_frameID, a_offsetX, a_offsetY)); if (a_frameID != null){ m_frameMap[a_frameID] = m_totalFrames; }; m_totalFrames++; return (m_frames[(m_frames.length - 1)].bitmapData[0]); } public function set isLooping(a_value:Boolean):void{ m_isLooping = a_value; } public function changeFrameCount(a_frameIndex:int, a_newFrameCount:int):void{ var frame:Frame = m_frames[a_frameIndex]; frame.numFrames = a_newFrameCount; } public function get isLooping():Boolean{ return (m_isLooping); } } }//package com.urbansquall.ginger
Section 98
//AnimationBuilder (com.urbansquall.ginger.AnimationBuilder) package com.urbansquall.ginger { import flash.display.*; import flash.geom.*; public class AnimationBuilder { public function AnimationBuilder(){ super(); } public static function importStrip(a_fps:int, a_bitmapData:BitmapData, a_tileWidth:int, a_tileHeight:int, a_tileCount:int=-1, a_startingX:int=0, a_startingY:int=0, a_rotations:int=1, a_offsetX:int=0, a_offsetY:int=0):Animation{ var frameLocation:Rectangle; var tileX:int; var tileY:int; var animation:Animation = new Animation(a_fps, a_rotations); var rows:int = Math.ceil((a_bitmapData.height / a_tileHeight)); var cols:int = Math.ceil((a_bitmapData.width / a_tileWidth)); if (a_tileCount == -1){ a_tileCount = (rows * cols); }; var i:int; while (i < a_tileCount) { tileX = (i % cols); tileY = Math.floor((i / cols)); frameLocation = new Rectangle((a_startingX + (tileX * a_tileWidth)), (a_startingY + (tileY * a_tileHeight)), a_tileWidth, a_tileHeight); animation.addFrame(1, a_bitmapData, frameLocation, ((a_tileWidth / 2) + a_offsetX), ((a_tileHeight / 2) + a_offsetY)); i++; }; return (animation); } } }//package com.urbansquall.ginger
Section 99
//AnimationEvent (com.urbansquall.ginger.AnimationEvent) package com.urbansquall.ginger { import flash.events.*; public class AnimationEvent extends Event { public var begin:Boolean; public var animationID:String; public static const CHANGE:String = "animation_event_change"; public function AnimationEvent(type:String, a_begin:Boolean, a_animationID:String, bubbles:Boolean=false, cancelable:Boolean=false){ super(type, bubbles, cancelable); begin = a_begin; animationID = a_animationID; } } }//package com.urbansquall.ginger
Section 100
//AnimationPlayer (com.urbansquall.ginger.AnimationPlayer) package com.urbansquall.ginger { import flash.events.*; import flash.display.*; import flash.utils.*; public class AnimationPlayer extends Sprite { private var m_framesMap:Dictionary; private var m_hasAnimationEnded:Boolean; private var m_currentFrame:Frame; private var m_rotation:Number;// = 0 private var m_desiredY:Number;// = 0 private var m_currentAnimation:Animation; private var m_fps:int; private var m_desiredX:Number;// = 0 private var m_IDArray:Array; private var m_defaultAnimationID:String; private var m_totalFrames:int; private var m_rotationFrame:int; private var m_frames:Array; private var m_bitmap:Bitmap; private var m_framesPassed:int; private var m_animationMap:Dictionary; private var m_isPlaying:Boolean; private var m_timerInterval:int;// = 0 private var m_isLooping:Boolean; private var m_animationDelay:int; private var m_timer:Timer; private var m_hasRotationChanged:Boolean; private var m_frameIndex:int; private var m_currentAnimationID:String; private var m_timeSinceLastUpdate:int; private var m_animationQueue:Array; public function AnimationPlayer(){ super(); m_IDArray = []; m_animationQueue = []; m_frames = []; m_animationMap = new Dictionary(); m_framesMap = new Dictionary(); m_bitmap = new Bitmap(null, "never", false); addChild(m_bitmap); } override public function set rotation(value:Number):void{ m_rotation = int(value); m_rotation = (m_rotation % 360); if (m_rotation < 0){ m_rotation = (m_rotation + 360); }; m_rotationFrame = Math.round((m_rotation / m_currentAnimation.m_degToRotBy)); if (m_rotationFrame >= m_currentAnimation.m_framesOfRotation){ m_rotationFrame = 0; }; m_hasRotationChanged = true; } override public function get x():Number{ return (m_desiredX); } public function togglePause():void{ if (m_currentAnimation != null){ m_isPlaying = !(m_isPlaying); }; } public function get fps():int{ return (m_fps); } override public function get rotation():Number{ return (m_rotation); } public function get currentFrameID():String{ return (m_currentFrame.frameID); } override public function set width(value:Number):void{ throw (new Error("<AnimationPlayer> Width / Height cannot be changed!")); } public function queue(a_animationID:String):void{ var animation:Animation = m_animationMap[a_animationID]; if (animation == null){ throw (new Error("<AnimationPlayer> Invalid Animation ID!")); }; m_animationQueue.push(a_animationID); } public function startSelfTick(a_interval:int):void{ if (a_interval <= 0){ return; }; stopSelfTick(); m_timerInterval = a_interval; m_timer = new Timer(m_timerInterval); m_timer.addEventListener(TimerEvent.TIMER, tickTimer, false, 0, true); m_timer.start(); this.addEventListener(Event.REMOVED_FROM_STAGE, handleRemovedFromStage, false, 0, true); } override public function set scaleX(a_value:Number):void{ super.scaleX = a_value; performOffset(); } public function get defaultAnimationID():String{ return (m_defaultAnimationID); } public function get offsetY():Number{ return (m_currentFrame.offsetY[m_rotationFrame]); } private function tickTimer(a_event:TimerEvent):void{ update(m_timerInterval); } public function stopSelfTick():void{ if (m_timer != null){ this.removeEventListener(Event.REMOVED_FROM_STAGE, handleRemovedFromStage, false); m_timer.removeEventListener(TimerEvent.TIMER, tickTimer, false); m_timer.stop(); m_timer = null; }; } override public function set scaleY(a_value:Number):void{ super.scaleY = a_value; performOffset(); } public function isPaused():Boolean{ return (m_isPlaying); } public function get offsetX():Number{ return (m_currentFrame.offsetX[m_rotationFrame]); } override public function set x(value:Number):void{ m_desiredX = value; performOffset(); } public function get animationIDs():Array{ return (m_IDArray.slice()); } public function set defaultAnimationID(value:String):void{ m_defaultAnimationID = value; } private function handleRemovedFromStage(a_event:Event):void{ stopSelfTick(); } override public function get width():Number{ return (m_currentFrame.width[m_rotationFrame]); } override public function get height():Number{ return (m_currentFrame.height[m_rotationFrame]); } public function play(a_animationID:String):void{ if (m_animationMap[a_animationID] == null){ throw (new Error((("<AnimationPlayer> Invalid Animation ID [" + a_animationID) + "]"))); }; m_isPlaying = true; m_hasAnimationEnded = false; m_animationQueue = [m_currentAnimation]; startNewAnimation(a_animationID); } private function startNewAnimation(a_animationID:String):void{ m_timeSinceLastUpdate = 0; m_currentAnimationID = a_animationID; m_currentAnimation = m_animationMap[m_currentAnimationID]; if (m_currentAnimation == null){ m_currentAnimationID = m_defaultAnimationID; m_currentAnimation = m_animationMap[m_currentAnimationID]; }; fps = m_currentAnimation.m_fps; m_frames = m_currentAnimation.m_frames; m_framesMap = m_currentAnimation.m_frameMap; m_isLooping = m_currentAnimation.isLooping; m_totalFrames = m_frames.length; m_frameIndex = 0; m_currentFrame = Frame(m_frames[0]); m_bitmap.bitmapData = m_currentFrame.bitmapData[m_rotationFrame]; performOffset(); if (hasEventListener(AnimationEvent.CHANGE)){ dispatchEvent(new AnimationEvent(AnimationEvent.CHANGE, true, m_currentAnimationID)); }; if (m_currentFrame.frameID != null){ if (hasEventListener(FrameEvent.CHANGE)){ dispatchEvent(new FrameEvent(FrameEvent.CHANGE, true, m_currentFrame.frameID, m_currentAnimationID)); }; }; } override public function set height(value:Number):void{ throw (new Error("<AnimationPlayer> Width / Height cannot be changed!")); } public function update(a_ms:Number):void{ var eventToDispatch:AnimationEvent; if (m_hasAnimationEnded){ eventToDispatch = null; if (hasEventListener(AnimationEvent.CHANGE)){ eventToDispatch = new AnimationEvent(AnimationEvent.CHANGE, false, m_currentAnimationID); }; if (m_isLooping){ startNewAnimation(m_animationQueue[0]); } else { if (m_animationQueue.length <= 1){ m_animationQueue.splice(0); if (m_currentAnimationID == m_defaultAnimationID){ m_isPlaying = false; } else { startNewAnimation(m_defaultAnimationID); }; } else { m_animationQueue.shift(); startNewAnimation(m_animationQueue[0]); }; }; m_hasAnimationEnded = false; if (eventToDispatch != null){ dispatchEvent(eventToDispatch); }; } else { if (m_hasRotationChanged){ m_bitmap.bitmapData = m_currentFrame.bitmapData[m_rotationFrame]; m_hasRotationChanged = false; }; }; if (m_isPlaying){ m_timeSinceLastUpdate = (m_timeSinceLastUpdate + a_ms); if (m_timeSinceLastUpdate > m_animationDelay){ m_timeSinceLastUpdate = (m_timeSinceLastUpdate - m_animationDelay); updateFrame(); }; }; } public function gotoFrame(a_frameID:String, a_animationID:String=null):void{ if (a_animationID != null){ startNewAnimation(a_animationID); }; var index:int = m_framesMap[a_frameID]; m_currentFrame = Frame(m_frames[index]); performOffset(); m_bitmap.bitmapData = (m_currentFrame.bitmapData[m_rotationFrame] as BitmapData); m_frameIndex = index; m_framesPassed = 0; m_isPlaying = false; if (m_currentFrame.frameID != null){ if (hasEventListener(FrameEvent.CHANGE)){ dispatchEvent(new FrameEvent(FrameEvent.CHANGE, true, m_currentFrame.frameID, m_currentAnimationID)); }; }; } private function performOffset():void{ var signX = -1; var signY = -1; if (scaleX < 0){ signX = 1; }; if (scaleY < 0){ signY = 1; }; super.x = (m_desiredX + (signX * offsetX)); super.y = (m_desiredY + (signY * offsetY)); } public function set fps(value:int):void{ m_fps = value; if (value <= 0){ m_fps = 0; m_animationDelay = 0; } else { m_fps = value; m_animationDelay = (1000 / value); }; } private function updateFrame():void{ if (m_currentFrame == null){ return; }; m_framesPassed++; if (m_framesPassed > m_currentFrame.numFrames){ m_framesPassed = 0; if (++m_frameIndex >= m_totalFrames){ if (!m_isLooping){ m_hasAnimationEnded = true; return; }; m_frameIndex = 0; }; m_currentFrame = Frame(m_frames[m_frameIndex]); m_bitmap.bitmapData = m_currentFrame.bitmapData[m_rotationFrame]; performOffset(); if (m_currentFrame.frameID != null){ if (hasEventListener(FrameEvent.CHANGE)){ dispatchEvent(new FrameEvent(FrameEvent.CHANGE, true, m_currentFrame.frameID, m_currentAnimationID)); }; }; }; } public function addAnimation(a_animationID:String, a_animation:Animation):void{ m_IDArray.push(a_animationID); m_animationMap[a_animationID] = a_animation; if (m_defaultAnimationID == null){ m_defaultAnimationID = a_animationID; play(a_animationID); performOffset(); }; } public function copy():AnimationPlayer{ var id:String; var player:AnimationPlayer = new AnimationPlayer(); var i:int; while (i < m_IDArray.length) { id = m_IDArray[i]; player.addAnimation(id, m_animationMap[id]); i++; }; player.defaultAnimationID = m_defaultAnimationID; player.fps = m_fps; player.play(m_defaultAnimationID); player.m_bitmap.bitmapData = m_bitmap.bitmapData; return (player); } public function get currentAnimationID():String{ return (m_currentAnimationID); } override public function set y(value:Number):void{ m_desiredY = value; performOffset(); } public function pause():void{ m_isPlaying = false; } override public function get y():Number{ return (m_desiredY); } public function unpause():void{ if (m_currentAnimation != null){ m_isPlaying = true; }; } } }//package com.urbansquall.ginger
Section 101
//AnimationPlayerFactory (com.urbansquall.ginger.AnimationPlayerFactory) package com.urbansquall.ginger { import flash.utils.*; public class AnimationPlayerFactory { private var m_animations:Dictionary; public function AnimationPlayerFactory(){ super(); m_animations = new Dictionary(); } public function instantiate(a_name:String):AnimationPlayer{ if (m_animations[a_name] == null){ throw (new Error((("AnimationFactory:instantiate. There is no animation with the name [" + a_name) + "]"))); }; var animationPlayer:AnimationPlayer = m_animations[a_name]; return (animationPlayer.copy()); } public function register(a_name:String, a_animationPlayer:AnimationPlayer):void{ if (m_animations[a_name] != null){ throw (new Error((("AnimationFactory:register. There is already an animation with the name [" + a_name) + "]"))); }; m_animations[a_name] = a_animationPlayer; } public function dispose():void{ var key:String; var animationPlayer:AnimationPlayer; for (key in m_animations) { animationPlayer = m_animations[key]; delete m_animations[key]; }; m_animations = null; } } }//package com.urbansquall.ginger
Section 102
//Frame (com.urbansquall.ginger.Frame) package com.urbansquall.ginger { import com.urbansquall.ginger.*; import flash.display.*; import flash.geom.*; class Frame { public var offsetX:Array; public var width:Array; public var height:Array; public var frameID:String; public var offsetY:Array; public var numFrames:int; public var bitmapData:Array; private var m_debugID:Number; function Frame(a_numFrames:int, a_bitmapData:BitmapData, a_numRotations:int, a_frameID:String, a_offsetX:Number=0, a_offsetY:Number=0){ super(); m_debugID = Math.random(); numFrames = a_numFrames; frameID = a_frameID; bitmapData = []; width = []; height = []; offsetX = []; offsetY = []; if (a_numRotations == 1){ createFrameWithNoRotation(a_bitmapData, a_offsetX, a_offsetY); } else { createRotatedFrame(a_bitmapData, a_numRotations, a_offsetX, a_offsetY); }; } private function createRotatedFrame(a_bitmapData:BitmapData, a_numRotations:int, a_offsetX:Number=0, a_offsetY:Number=0):void{ var tileWidth:int = a_bitmapData.width; var tileHeight:int = a_bitmapData.height; var tx:Number = ((tileWidth / 2) * Math.SQRT2); var ty:Number = ((tileHeight / 2) * Math.SQRT2); var maxTxy:Number = Math.max(tx, ty); var bdSize:Number = Math.ceil((Math.max(tileWidth, tileHeight) * Math.SQRT2)); var mat:Matrix = new Matrix(1, 0, 0, 1, maxTxy, maxTxy); var bd:BitmapData = new BitmapData(bdSize, bdSize, true, 0); var container:Sprite = new Sprite(); var bmpHolder:Sprite = new Sprite(); var bmpData:BitmapData = new BitmapData(tileWidth, tileHeight, true, 0); var bmp:Bitmap = new Bitmap(a_bitmapData, "never", false); bmp.x = -((tileWidth / 2)); bmp.y = -((tileHeight / 2)); bmpHolder.addChild(bmp); container.addChild(bmpHolder); var ri:int; while (ri < a_numRotations) { bd.fillRect(bd.rect, 0); bd.draw(container, mat); bitmapData[ri] = bd.clone(); width[ri] = bmpHolder.width; height[ri] = bmpHolder.height; offsetX[ri] = (a_offsetX + ((bd.width - tileWidth) / 2)); offsetY[ri] = (a_offsetY + ((bd.height - tileHeight) / 2)); bmpHolder.rotation = (bmpHolder.rotation + (360 / a_numRotations)); ri++; }; } public function toString():String{ return ((((((((((((("<Frame (" + m_debugID) + ") bitmapData:") + bitmapData.length) + " numFrames:") + numFrames) + " frameID:") + frameID) + " offsetX:") + offsetX) + " offsetY:") + offsetY) + ">")); } public function changeID(a_id:String):void{ frameID = a_id; } private function createFrameWithNoRotation(a_bitmapData:BitmapData, a_offsetX:Number=0, a_offsetY:Number=0):void{ bitmapData.push(a_bitmapData); width.push(a_bitmapData.width); height.push(a_bitmapData.height); offsetX.push(a_offsetX); offsetY.push(a_offsetY); } } }//package com.urbansquall.ginger
Section 103
//FrameEvent (com.urbansquall.ginger.FrameEvent) package com.urbansquall.ginger { import flash.events.*; public class FrameEvent extends Event { public var frameID:String; public var begin:Boolean; public var animationID:String; public static const CHANGE:String = "frame_event_change"; public function FrameEvent(type:String, a_begin:Boolean, a_frameID:String, a_animationID:String, bubbles:Boolean=false, cancelable:Boolean=false){ super(type, bubbles, cancelable); begin = a_begin; frameID = a_frameID; animationID = a_animationID; } } }//package com.urbansquall.ginger
Section 104
//DieOnTouchSomethingBehavior (com.urbansquall.prophet.behaviors.DieOnTouchSomethingBehavior) package com.urbansquall.prophet.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class DieOnTouchSomethingBehavior extends Behavior { private var m_touchingSomething:Boolean;// = false public var ignoreSensors:Boolean;// = true public function DieOnTouchSomethingBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (((ignoreSensors) && (a_touchEvent.theirShape.IsSensor()))){ return; }; entity.getEngine().destroyEntity(entity.id); } override public function dispose():void{ } } }//package com.urbansquall.prophet.behaviors
Section 105
//ExpireBehavior (com.urbansquall.prophet.behaviors.ExpireBehavior) package com.urbansquall.prophet.behaviors { import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.prophet.utils.*; public class ExpireBehavior extends Behavior { public var expireEnabled:Boolean;// = false public var tweenOut:Boolean;// = false private var m_tweeningOut:Boolean;// = false public var tweenOutTime:Number;// = 1000 public var livingTime:Number;// = 5000 public function ExpireBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); if (entity.properties.exists("expireEnabled")){ expireEnabled = entity.properties.getBoolean("expireEnabled", true); }; } private function expire():void{ if (entity != null){ if (entity.getEngine() != null){ entity.getEngine().destroyEntity(entity.id); }; }; } override public function tick(a_interval:Number):void{ var tweenTime:Number; var g:int; var graphic:Graphic; if (m_tweeningOut){ return; }; if (!expireEnabled){ return; }; if (livingTime <= 0){ return; }; livingTime = (livingTime - a_interval); if (livingTime <= 0){ if (((!(tweenOut)) || ((entity.graphics.length == 0)))){ expire(); } else { m_tweeningOut = true; tweenTime = (tweenOutTime / 1000); g = 0; while (g < entity.graphics.length) { graphic = entity.graphics[g]; if (g == 0){ Tweener.addTween(graphic.display, {alpha:0.1, time:tweenTime, onComplete:expire, onCompleteParams:[]}); } else { Tweener.addTween(graphic.display, {alpha:0.1, time:tweenTime}); }; g++; }; }; }; } override public function dispose():void{ var graphic:Graphic; var g:int; while (g < entity.graphics.length) { graphic = entity.graphics[g]; Tweener.removeTweens(graphic); g++; }; } } }//package com.urbansquall.prophet.behaviors
Section 106
//OnRectangularGroundDetectionBehavior (com.urbansquall.prophet.behaviors.OnRectangularGroundDetectionBehavior) package com.urbansquall.prophet.behaviors { import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Common.Math.*; public class OnRectangularGroundDetectionBehavior extends Behavior { public var groundSensorOffsetX:Number;// = 0 public var groundSensorWidth:Number;// = 3 private var m_debugGraphic:Graphic;// = null public var groundSensorCollisionGroupIndex:int;// = 0 public var groundSensorOffsetY:Number;// = 0 public var groundSensorHeight:Number;// = 3 public var isDebugEnabled:Boolean;// = true public function OnRectangularGroundDetectionBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.myShape.GetUserData() == this){ if ((((a_touchEvent.theirEntity == null)) || (!(a_touchEvent.theirEntity.properties.getBoolean("canBeStoodOn", true))))){ return; }; if (a_touchEvent.theirShape.IsSensor()){ return; }; testGround(a_touchEvent.theirEntity, a_touchEvent.normal); }; } override public function createShapes():Array{ var groundSensor:PolygonDef; var def:PolygonGraphicDefinition; var graphic:Graphic; groundSensor = new PolygonDef(); groundSensor.makeCenteredBox((groundSensorWidth / 2), (groundSensorHeight / 2), groundSensorOffsetX, groundSensorOffsetY); groundSensor.isSensor = true; groundSensor.userData = this; groundSensor.groupFilter = groundSensorCollisionGroupIndex; if (isDebugEnabled){ def = new PolygonGraphicDefinition(1000, "groundSensor", groundSensor, 0xFF0000, 0xFF0000); graphic = def.createGraphic(1); entity.addGraphic(graphic); entity.getEngine().renderer.addDisplayObject(graphic.display, EngineRenderer.DEBUG_LAYER); }; return ([groundSensor]); } override public function postTick():void{ var properties:KeyValueMap = entity.properties; properties.setBoolean("standingOnSomething", false); properties.setNumber("groundNormalX", 0); properties.setNumber("groundNormalY", -1); } private function testGround(a_entity:Entity, a_normal:b2Vec2):void{ var properties:KeyValueMap = entity.properties; properties.setBoolean("standingOnSomething", true); properties.setNumber("groundNormalX", a_normal.x); properties.setNumber("groundNormalY", a_normal.y); var time:int = properties.getNumber("timeSinceLastStandingOnSomething", 0); if (time > 0){ properties.setNumber("previousTimeSinceLastStandingOnSomething", time); }; if (a_entity != null){ properties.setString("standingOnID", a_entity.id); } else { properties.setString("standingOnID", ""); }; properties.setNumber("timeSinceLastStandingOnSomething", 0); if (isDebugEnabled){ if (m_debugGraphic != null){ m_debugGraphic.display.visible = true; }; }; } override public function tick(a_deltaTime:Number):void{ if (isDebugEnabled){ if (m_debugGraphic == null){ m_debugGraphic = entity.lookupGraphic("groundSensor"); }; m_debugGraphic.display.visible = false; }; var properties:KeyValueMap = entity.properties; if (properties.getBoolean("standingOnSomething", false)){ properties.setNumber("timeOfStandingOnSomething", (properties.getNumber("timeOfStandingOnSomething", 0) + a_deltaTime)); } else { properties.setNumber("timeOfStandingOnSomething", 0); }; properties.setNumber("timeSinceLastStandingOnSomething", (properties.getNumber("timeSinceLastStandingOnSomething", 0) + a_deltaTime)); } override public function dispose():void{ } } }//package com.urbansquall.prophet.behaviors
Section 107
//BehaviorDefinition (com.urbansquall.prophet.definitions.BehaviorDefinition) package com.urbansquall.prophet.definitions { import com.urbansquall.prophet.utils.*; public class BehaviorDefinition { private var m_type:Class; private var m_data:KeyValueMap; private var m_name:String; public function BehaviorDefinition(a_type:Class, a_name:String, a_data:KeyValueMap=null){ super(); m_type = a_type; m_data = a_data; m_name = a_name; } public function get type():Class{ return (m_type); } public function clone():BehaviorDefinition{ var myClone:BehaviorDefinition = new BehaviorDefinition(m_type, m_name, ((m_data == null)) ? null : m_data.clone()); return (myClone); } public function get data():KeyValueMap{ return (m_data); } public function get name():String{ return (m_name); } } }//package com.urbansquall.prophet.definitions
Section 108
//BitmapGraphicDefinition (com.urbansquall.prophet.definitions.BitmapGraphicDefinition) package com.urbansquall.prophet.definitions { import flash.display.*; import com.urbansquall.prophet.engine.*; public class BitmapGraphicDefinition extends GraphicDefinition { private var m_center:Boolean; private var m_bitmapData:BitmapData; private var m_name:String; public function BitmapGraphicDefinition(a_renderLayer:int, a_name:String, a_bitmapData:BitmapData, a_center:Boolean=true){ super(a_renderLayer); m_name = a_name; m_bitmapData = a_bitmapData; m_center = a_center; } public function get name():String{ return (m_name); } override public function createGraphic(a_scale:Number):Graphic{ var displayObject:DisplayObject; displayObject = new Bitmap(m_bitmapData); var container:Sprite = new Sprite(); container.addChild(displayObject); if (m_center){ displayObject.x = (displayObject.x - (displayObject.width / 2)); displayObject.y = (displayObject.y - (displayObject.height / 2)); }; return (new Graphic(container, m_name)); } } }//package com.urbansquall.prophet.definitions
Section 109
//CircleGraphicDefinition (com.urbansquall.prophet.definitions.CircleGraphicDefinition) package com.urbansquall.prophet.definitions { import flash.display.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.physics.*; public class CircleGraphicDefinition extends GraphicDefinition { private var m_radius:Number; private var m_offset:Point; private var m_lineColor:uint; private var m_fillColor:uint; private var m_name:String; public function CircleGraphicDefinition(a_renderLayer:int, a_name:String, a_circleDef:CircleDef, a_fillColor:uint, a_lineColor:uint){ super(a_renderLayer); m_offset = new Point(); m_offset.x = a_circleDef.localPosition.x; m_offset.y = a_circleDef.localPosition.y; m_radius = a_circleDef.radius; m_fillColor = a_fillColor; m_lineColor = a_lineColor; m_name = a_name; } override public function createGraphic(a_scale:Number):Graphic{ var sprite:Sprite = new Sprite(); sprite.graphics.beginFill(m_fillColor, 0.5); sprite.graphics.lineStyle(1, m_lineColor, 0.5); sprite.graphics.drawCircle((a_scale * m_offset.x), (a_scale * m_offset.y), (a_scale * m_radius)); sprite.graphics.moveTo(m_radius, 0); sprite.graphics.lineTo((m_radius / 2), 0); return (new Graphic(sprite, m_name)); } } }//package com.urbansquall.prophet.definitions
Section 110
//EntityTypeDefinition (com.urbansquall.prophet.definitions.EntityTypeDefinition) package com.urbansquall.prophet.definitions { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Dynamics.*; public class EntityTypeDefinition { public var behaviors:Array; public var physics:b2BodyDef;// = null public var graphics:Array; public var shapes:Array; public var properties:KeyValueMap; public var fixed:Boolean;// = false public var editorGraphics:Array; private var m_pruneType:String;// = "normal" public var type:String;// = "" public function EntityTypeDefinition(){ shapes = []; behaviors = []; graphics = []; editorGraphics = []; properties = new KeyValueMap(); super(); } public function set pruneType(value:String):void{ if (value == PruneType.INHERIT){ throw (new Error("PruneType.INHERIT is an invalid value for pruneType on EntityTypeDefinitions.")); }; m_pruneType = value; } public function get pruneType():String{ return (m_pruneType); } public function clone():EntityTypeDefinition{ var g:int; var graphic:GraphicDefinition; var shape:ShapeDef; var behavior:BehaviorDefinition; var myClone:EntityTypeDefinition = new EntityTypeDefinition(); myClone.type = type; var s:int; while (s < shapes.length) { shape = shapes[s]; myClone.shapes.push(shape.clone()); s++; }; var b:int; while (b < behaviors.length) { behavior = behaviors[b]; myClone.behaviors.push(behavior.clone()); b++; }; myClone.physics = physics; myClone.fixed = fixed; g = 0; while (g < graphics.length) { graphic = graphics[g]; myClone.graphics.push(graphic); g++; }; g = 0; while (g < editorGraphics.length) { graphic = editorGraphics[g]; myClone.editorGraphics.push(graphic); g++; }; myClone.properties = properties.clone(); myClone.pruneType = pruneType; return (myClone); } } }//package com.urbansquall.prophet.definitions
Section 111
//GameDefinition (com.urbansquall.prophet.definitions.GameDefinition) package com.urbansquall.prophet.definitions { import flash.utils.*; public class GameDefinition { private var m_entityDefinitionList:Array; private var m_entityDefinitions:Dictionary; public function GameDefinition(){ m_entityDefinitions = new Dictionary(); m_entityDefinitionList = []; super(); } public function registerEntityType(a_entityDefinition:EntityTypeDefinition):void{ if (a_entityDefinition.type == ""){ throw (new Error("Entity Definition requires type")); }; m_entityDefinitions[a_entityDefinition.type] = a_entityDefinition; m_entityDefinitionList.push(a_entityDefinition); } public function removeEntityType(a_type:String):void{ var e:EntityTypeDefinition; if (m_entityDefinitions[a_type] == null){ return; }; delete m_entityDefinitions[a_type]; var i:int; while (i < m_entityDefinitionList.length) { e = m_entityDefinitionList[i]; if (e.type == a_type){ m_entityDefinitionList.splice(i, 1); return; }; i++; }; } public function clone():GameDefinition{ var entityTypeDefinition:EntityTypeDefinition; var myClone:GameDefinition = new GameDefinition(); var i:int; while (i < m_entityDefinitionList.length) { entityTypeDefinition = m_entityDefinitionList[i]; myClone.registerEntityType(entityTypeDefinition.clone()); i++; }; return (myClone); } public function lookupEntityType(a_entityType:String):EntityTypeDefinition{ return (m_entityDefinitions[a_entityType]); } public function getIndexedEntityDefinition(a_index:int):EntityTypeDefinition{ return (m_entityDefinitionList[a_index]); } public function get entityDefinitionCount():int{ return (m_entityDefinitionList.length); } } }//package com.urbansquall.prophet.definitions
Section 112
//GingerGraphicDefinition (com.urbansquall.prophet.definitions.GingerGraphicDefinition) package com.urbansquall.prophet.definitions { import com.urbansquall.ginger.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; public class GingerGraphicDefinition extends GraphicDefinition { private var m_gingerName:String; private var m_defaultAnimation:String; private var m_name:String; public function GingerGraphicDefinition(a_renderLayer:int, a_name:String, a_gingerName:String, a_defaultAnimation:String=""){ super(a_renderLayer); m_name = a_name; m_gingerName = a_gingerName; m_defaultAnimation = a_defaultAnimation; } override public function createGraphic(a_scale:Number):Graphic{ var animationPlayer:AnimationPlayer = GingerFactory.getInstance().instantiate(m_gingerName); if (m_defaultAnimation != ""){ animationPlayer.defaultAnimationID = m_defaultAnimation; }; return (new GingerGraphic(animationPlayer, m_name)); } } }//package com.urbansquall.prophet.definitions
Section 113
//GraphicDefinition (com.urbansquall.prophet.definitions.GraphicDefinition) package com.urbansquall.prophet.definitions { import com.urbansquall.prophet.engine.*; public class GraphicDefinition { private var m_renderLayer:int; public function GraphicDefinition(a_renderLayer:int){ super(); m_renderLayer = a_renderLayer; } public function createGraphic(a_scale:Number):Graphic{ throw (new Error("Not defined")); } public function get renderLayer():int{ return (m_renderLayer); } } }//package com.urbansquall.prophet.definitions
Section 114
//LevelDefinition (com.urbansquall.prophet.definitions.LevelDefinition) package com.urbansquall.prophet.definitions { import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class LevelDefinition { private var m_dataDump:KeyValueMap; private var m_worldBounds:Rectangle; private var m_spawnInfos:Array; private var m_allowSleep:Boolean;// = false private var m_levelGraphics:Array; private var m_gravity:Point; public function LevelDefinition(){ m_spawnInfos = []; m_levelGraphics = []; super(); m_dataDump = new KeyValueMap(); m_worldBounds = new Rectangle(0, 0, 640, 480); m_gravity = new Point(0, 0); } public function setDataDump(a_dataDump:KeyValueMap):void{ m_dataDump = a_dataDump; } public function addLevelGraphic(a_levelGraphic:LevelGraphicDefinition):void{ m_levelGraphics.push(a_levelGraphic); } public function get gravityX():Number{ return (m_gravity.x); } public function get gravityY():Number{ return (m_gravity.y); } public function setGravity(a_x:Number, a_y:Number):void{ m_gravity = new Point(a_x, a_y); } public function get worldBoundY():int{ return (m_worldBounds.y); } public function get allowSleep():Boolean{ return (m_allowSleep); } public function getSpawnInfos():Array{ return (m_spawnInfos); } public function get worldBoundHeight():int{ return (m_worldBounds.height); } public function setAllowSleep(a_allowSleep:Boolean):void{ m_allowSleep = a_allowSleep; } public function get worldBoundWidth():int{ return (m_worldBounds.width); } public function get worldBoundX():int{ return (m_worldBounds.x); } public function clone():LevelDefinition{ var mySpawnInfo:EntitySpawnInfo; var result:LevelDefinition = new LevelDefinition(); result.m_worldBounds = this.m_worldBounds.clone(); result.m_gravity = this.m_gravity.clone(); var i:int; while (i < this.m_spawnInfos.length) { mySpawnInfo = this.m_spawnInfos[i]; result.m_spawnInfos.push(mySpawnInfo.clone()); i++; }; result.m_allowSleep = this.m_allowSleep; result.m_dataDump = this.m_dataDump.clone(); return (result); } public function setWorldBounds(a_x:int, a_y:int, a_width:int, a_height:int):void{ m_worldBounds = new Rectangle(a_x, a_y, a_width, a_height); } public function addSpawnInfo(a_spawnInfo:EntitySpawnInfo):void{ m_spawnInfos.push(a_spawnInfo); } public function removeSpawnInfo(a_id:String):void{ var spawnInfo:EntitySpawnInfo; var i:int; while (i < m_spawnInfos.length) { spawnInfo = m_spawnInfos[i]; if (a_id == spawnInfo.id){ m_spawnInfos.splice(i, 1); return; }; i++; }; } public function createSpawnInfo(a_type:String, a_id:String, a_x:Number, a_y:Number, a_vx:Number, a_vy:Number, a_rotation:Number=0, a_scale:Number=1, a_data:KeyValueMap=null):void{ addSpawnInfo(new EntitySpawnInfo(a_type, a_id, a_x, a_y, a_vx, a_vy, a_rotation, a_scale, a_data)); } public function setSpawnInfos(a_array:Array):void{ m_spawnInfos = a_array; } public function getDataDump():KeyValueMap{ return (m_dataDump); } public function getLevelGraphics():Array{ return (m_levelGraphics); } } }//package com.urbansquall.prophet.definitions
Section 115
//LevelGraphicDefinition (com.urbansquall.prophet.definitions.LevelGraphicDefinition) package com.urbansquall.prophet.definitions { public class LevelGraphicDefinition { private var m_x:Number; private var m_y:Number; private var m_graphicDef:GraphicDefinition; public function LevelGraphicDefinition(a_x:Number, a_y:Number, a_graphicDefinition:GraphicDefinition){ super(); m_x = a_x; m_y = a_y; m_graphicDef = a_graphicDefinition; } public function get x():Number{ return (m_x); } public function get y():Number{ return (m_y); } public function get graphicDef():GraphicDefinition{ return (m_graphicDef); } } }//package com.urbansquall.prophet.definitions
Section 116
//PolygonGraphicDefinition (com.urbansquall.prophet.definitions.PolygonGraphicDefinition) package com.urbansquall.prophet.definitions { import flash.display.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.physics.*; public class PolygonGraphicDefinition extends GraphicDefinition { private var m_name:String; private var m_vertices:Array; private var m_lineColor:uint; private var m_fillColor:uint; public function PolygonGraphicDefinition(a_renderLayer:int, a_name:String, a_polygonDef:PolygonDef, a_fillColor:uint, a_lineColor:uint){ m_vertices = []; super(a_renderLayer); m_vertices = a_polygonDef.getVerticesCopy(); m_fillColor = a_fillColor; m_lineColor = a_lineColor; m_name = a_name; } override public function createGraphic(a_scale:Number):Graphic{ var vertex:Point; var sprite:Sprite = new Sprite(); sprite.graphics.beginFill(m_fillColor, 0.5); sprite.graphics.lineStyle(2, m_lineColor, 0.5); var v:int; while (v < m_vertices.length) { vertex = m_vertices[v]; if (v == 0){ sprite.graphics.moveTo((vertex.x * a_scale), (vertex.y * a_scale)); } else { sprite.graphics.lineTo((vertex.x * a_scale), (vertex.y * a_scale)); }; v++; }; return (new Graphic(sprite, m_name)); } } }//package com.urbansquall.prophet.definitions
Section 117
//StaticGraphicDefinition (com.urbansquall.prophet.definitions.StaticGraphicDefinition) package com.urbansquall.prophet.definitions { import flash.display.*; import com.urbansquall.prophet.engine.*; public class StaticGraphicDefinition extends GraphicDefinition { private var m_scaleX:Number; private var m_scaleY:Number; private var m_class:Class; private var m_offsetX:Number; private var m_offsetY:Number; private var m_rotates:Boolean; private var m_name:String; public function StaticGraphicDefinition(a_renderLayer:int, a_name:String, a_class:Class, a_offsetX:Number=0, a_offsetY:Number=0, a_rotates:Boolean=true, a_scaleX:Number=1, a_scaleY:Number=1){ super(a_renderLayer); m_class = a_class; m_name = a_name; m_offsetX = a_offsetX; m_offsetY = a_offsetY; m_rotates = a_rotates; m_scaleX = a_scaleX; m_scaleY = a_scaleY; } override public function createGraphic(a_scale:Number):Graphic{ var displayObject:DisplayObject; var bitmap:Bitmap; var a_scale = a_scale; displayObject = new m_class(); //unresolved jump var _slot1 = e; bitmap = new Bitmap(new m_class(0, 0)); displayObject = bitmap; var container:Sprite = new Sprite(); trace(m_name, m_scaleX); displayObject.scaleX = m_scaleX; displayObject.scaleY = m_scaleY; container.addChild(displayObject); displayObject.x = (displayObject.x - (displayObject.width / 2)); displayObject.y = (displayObject.y - (displayObject.height / 2)); displayObject.x = (displayObject.x + m_offsetX); displayObject.y = (displayObject.y + m_offsetY); var graphic:Graphic = new Graphic(container, m_name); graphic.rotates = m_rotates; return (graphic); } public function get graphicClass():Class{ return (m_class); } public function get name():String{ return (m_name); } } }//package com.urbansquall.prophet.definitions
Section 118
//TileLibrary (com.urbansquall.prophet.definitions.TileLibrary) package com.urbansquall.prophet.definitions { import com.urbansquall.prophet.tilemaps.*; import flash.utils.*; public class TileLibrary { private var m_tileDefinitions:Dictionary; private var m_tileSetNames:Array; private var m_drawDirection:int; private var m_tileWidth:int; private var m_tileDefinitionList:Array; private var m_tileHeight:int; public static const DRAW_DIRECTION_TOP_TO_BOTTOM:int = 0; public static const DRAW_DIRECTION_BOTTOM_TO_TOP:int = 1; public function TileLibrary(a_tileWidth:int, a_tileHeight:int, a_drawDirection:int){ m_tileDefinitions = new Dictionary(); m_tileDefinitionList = new Array(); m_tileSetNames = new Array(); super(); m_tileWidth = a_tileWidth; m_tileHeight = a_tileHeight; m_drawDirection = a_drawDirection; } public function getIndexedTileDefinition(a_index:int):TileDefinition{ return (m_tileDefinitionList[a_index]); } public function registerTileDefinition(a_tileDefinition:TileDefinition):void{ if (a_tileDefinition.name == ""){ throw (new Error("Tile Definition requires name")); }; if (a_tileDefinition.setName == ""){ a_tileDefinition.setName = "none"; }; if (m_tileSetNames.indexOf(a_tileDefinition.setName) < 0){ m_tileSetNames.push(a_tileDefinition.setName); }; m_tileDefinitions[a_tileDefinition.name] = a_tileDefinition; m_tileDefinitionList.push(a_tileDefinition); } public function get drawDirection():int{ return (m_drawDirection); } public function get tileHeight():int{ return (m_tileHeight); } public function get tileWidth():int{ return (m_tileWidth); } public function lookupTileDefinition(a_name:String):TileDefinition{ return (m_tileDefinitions[a_name]); } public function getSetNames():Array{ return (m_tileSetNames); } public function get tileDefinitionCount():int{ return (m_tileDefinitionList.length); } } }//package com.urbansquall.prophet.definitions
Section 119
//DebugDraw (com.urbansquall.prophet.display.DebugDraw) package com.urbansquall.prophet.display { public class DebugDraw { public var drawQueries:Boolean;// = false public var drawPhysicsShapes:Boolean;// = false public var drawLevelBoundaries:Boolean;// = false public function DebugDraw(){ super(); } } }//package com.urbansquall.prophet.display
Section 120
//EngineRenderer (com.urbansquall.prophet.display.EngineRenderer) package com.urbansquall.prophet.display { import flash.display.*; import flash.geom.*; import flash.utils.*; public class EngineRenderer { private var m_renderWidth:int; private var m_layerMap:Dictionary; private var m_debugDraw:DebugDraw; private var m_renderHeight:int; private var m_container:Sprite; private var m_layerList:Array; private var m_view:View; public static const DEBUG_LAYER:int = 2147483647; public function EngineRenderer(a_container:Sprite, a_renderWidth:int, a_renderHeight:int, a_debugDraw:DebugDraw){ m_layerList = new Array(); m_layerMap = new Dictionary(); super(); m_container = a_container; m_renderWidth = a_renderWidth; m_renderHeight = a_renderHeight; if (a_debugDraw == null){ a_debugDraw = new DebugDraw(); }; m_debugDraw = a_debugDraw; m_view = new View(this); } public function addDisplayObject(a_graphic:DisplayObject, a_renderLayer:int):void{ var layer:Sprite = m_layerMap[a_renderLayer]; if (layer == null){ createLayer(a_renderLayer); layer = m_layerMap[a_renderLayer]; }; layer.addChild(a_graphic); } public function removeDisplayObject(a_graphic:DisplayObject):void{ if (a_graphic.parent != null){ a_graphic.parent.removeChild(a_graphic); }; } public function lookupRenderLayer(a_renderLayer:int, a_createLayerIfMissing:Boolean=true):Sprite{ var layer:Sprite = m_layerMap[a_renderLayer]; if ((((layer == null)) && (a_createLayerIfMissing))){ createLayer(a_renderLayer); layer = m_layerMap[a_renderLayer]; }; return (layer); } public function get renderContainer():Sprite{ return (m_container); } public function clear():void{ var renderLayer:int; var i:int; while (i < m_layerList.length) { renderLayer = m_layerList[i]; m_container.removeChild(m_layerMap[renderLayer]); delete m_layerMap[renderLayer]; i++; }; m_layerList.splice(0); } public function get renderWidth():int{ return (m_renderWidth); } public function get mouseX():Number{ return (m_container.mouseX); } public function get mouseY():Number{ return (m_container.mouseY); } private function createLayer(a_renderLayer:int):void{ var layer:Sprite = new Sprite(); m_container.addChild(layer); m_layerMap[a_renderLayer] = layer; m_layerList.push(a_renderLayer); m_layerList.sort(Array.NUMERIC); var i:int; while (i < m_layerList.length) { m_container.setChildIndex(m_layerMap[m_layerList[i]], i); i++; }; } public function get renderHeight():int{ return (m_renderHeight); } public function enableMouse(a_renderLayer:int):void{ var layer:Sprite = m_layerMap[a_renderLayer]; if (layer == null){ createLayer(a_renderLayer); layer = m_layerMap[a_renderLayer]; }; layer.mouseChildren = true; layer.mouseEnabled = true; } public function get view():View{ return (m_view); } public function disableMouse(a_renderLayer:int):void{ var layer:Sprite = m_layerMap[a_renderLayer]; if (layer == null){ createLayer(a_renderLayer); layer = m_layerMap[a_renderLayer]; }; layer.mouseChildren = false; layer.mouseEnabled = false; } public function get debugDraw():DebugDraw{ return (m_debugDraw); } function moveTo(a_x:Number, a_y:Number):void{ m_container.scrollRect = new Rectangle((a_x - (m_renderWidth / 2)), (a_y - (m_renderHeight / 2)), m_renderWidth, m_renderHeight); } public function tick(a_interval:Number):void{ m_view.tick(a_interval); } } }//package com.urbansquall.prophet.display
Section 121
//GingerFactory (com.urbansquall.prophet.display.GingerFactory) package com.urbansquall.prophet.display { import com.urbansquall.ginger.*; public class GingerFactory extends AnimationPlayerFactory { private static var s_instance:GingerFactory = null; public function GingerFactory(){ super(); if (s_instance != null){ throw (new Error("can't instantiate two ginger factories!")); }; s_instance = this; } public static function getInstance():GingerFactory{ if (s_instance == null){ new (GingerFactory); }; return (s_instance); } } }//package com.urbansquall.prophet.display
Section 122
//View (com.urbansquall.prophet.display.View) package com.urbansquall.prophet.display { import flash.geom.*; public class View { private var m_viewX:Number;// = 0 private var m_speedX:Number;// = -1 private var m_speedY:Number;// = -1 private var m_viewY:Number;// = 0 private var m_upperBound:Point; private var m_lowerBound:Point; private var m_targetX:Number;// = 0 private var m_targetY:Number;// = 0 private var m_shakeVector:Point;// = null private var m_shakeViewTimer:Number;// = -1 private var m_renderer:EngineRenderer; private var m_tensionX:Number;// = -1 private var m_tensionY:Number;// = -1 private var m_temporaryUpperBound:Point;// = null private var m_shakeSize:Number; private var m_maxSeparationX:Number;// = INF private var m_maxSeparationY:Number;// = INF private var m_temporaryLowerBound:Point;// = null public static const INFINITE_SPEED:Number = -1; public function View(a_renderer:EngineRenderer){ super(); m_renderer = a_renderer; m_targetX = (m_renderer.renderWidth / 2); m_targetY = (m_renderer.renderHeight / 2); m_viewX = m_targetX; m_viewY = m_targetY; m_lowerBound = new Point(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); m_upperBound = new Point(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); } public function set tensionX(value:Number):void{ m_tensionX = value; } public function setTarget(a_x:Number, a_y:Number):void{ m_targetX = a_x; m_targetY = a_y; m_targetX = Math.max(m_targetX, m_lowerBound.x); m_targetX = Math.min(m_targetX, m_upperBound.x); m_targetY = Math.max(m_targetY, m_lowerBound.y); m_targetY = Math.min(m_targetY, m_upperBound.y); } public function set tensionY(value:Number):void{ m_tensionY = value; } public function set maxSeparationX(value:Number):void{ m_maxSeparationX = value; } public function setTemporaryBounds(a_x:Number, a_y:Number, a_width:Number, a_height:Number, a_limitToPermanentBounds:Boolean=true):void{ m_temporaryLowerBound = new Point(); m_temporaryUpperBound = new Point(); m_temporaryLowerBound.x = (a_x + (m_renderer.renderWidth / 2)); m_temporaryLowerBound.y = (a_y + (m_renderer.renderHeight / 2)); m_temporaryUpperBound.x = ((a_x + a_width) - (m_renderer.renderWidth / 2)); m_temporaryUpperBound.y = ((a_y + a_height) - (m_renderer.renderHeight / 2)); if (a_limitToPermanentBounds){ m_temporaryLowerBound.x = Math.max(m_temporaryLowerBound.x, m_lowerBound.x); m_temporaryLowerBound.y = Math.max(m_temporaryLowerBound.y, m_lowerBound.y); m_temporaryUpperBound.x = Math.min(m_temporaryUpperBound.x, m_upperBound.x); m_temporaryUpperBound.y = Math.min(m_temporaryUpperBound.y, m_upperBound.y); }; } public function set maxSeparationY(value:Number):void{ m_maxSeparationY = value; } public function setView(a_x:Number, a_y:Number):void{ m_viewX = a_x; m_viewY = a_y; } public function tick(a_interval:Number):void{ var separationX:Number; var displacementX:Number; var separationY:Number; var displacementY:Number; if (m_speedX >= 0){ separationX = (m_targetX - m_viewX); displacementX = (a_interval * m_speedX); if (separationX < 0){ displacementX = (displacementX * -1); }; if (m_tensionX > 0){ displacementX = (displacementX + (separationX * m_tensionX)); }; if (Math.abs(separationX) < Math.abs(displacementX)){ displacementX = separationX; }; m_viewX = (m_viewX + displacementX); if (Math.abs((m_targetX - m_viewX)) > m_maxSeparationX){ if (m_targetX < m_viewX){ m_viewX = (m_targetX + m_maxSeparationX); } else { m_viewX = (m_targetX - m_maxSeparationX); }; }; } else { m_viewX = m_targetX; }; if (m_speedY >= 0){ separationY = (m_targetY - m_viewY); displacementY = (a_interval * m_speedY); if (separationY < 0){ displacementY = (displacementY * -1); }; if (m_tensionY > 0){ displacementY = (displacementY + (separationY * m_tensionY)); }; if (Math.abs(separationY) < Math.abs(displacementY)){ displacementY = separationY; }; m_viewY = (m_viewY + displacementY); if (Math.abs((m_targetY - m_viewY)) > m_maxSeparationY){ if (m_targetY < m_viewY){ m_viewY = (m_targetY + m_maxSeparationY); } else { m_viewY = (m_targetY - m_maxSeparationY); }; }; } else { m_viewY = m_targetY; }; if (m_temporaryLowerBound != null){ m_viewX = Math.max(m_viewX, m_temporaryLowerBound.x); m_viewX = Math.min(m_viewX, m_temporaryUpperBound.x); m_viewY = Math.max(m_viewY, m_temporaryLowerBound.y); m_viewY = Math.min(m_viewY, m_temporaryUpperBound.y); }; if (m_shakeViewTimer > 0){ m_shakeViewTimer = (m_shakeViewTimer - a_interval); if ((((Math.random() < 0.5)) || ((m_shakeVector == null)))){ m_shakeVector = new Point(); m_shakeVector.x = ((Math.random() * 2) - 1); m_shakeVector.y = ((Math.random() * 2) - 1); if (m_shakeVector.length == 0){ m_shakeVector = null; return; }; m_shakeVector.normalize(m_shakeSize); }; if (m_shakeVector != null){ m_viewX = (m_viewX + m_shakeVector.x); m_viewY = (m_viewY + m_shakeVector.y); }; }; if (m_temporaryLowerBound == null){ m_viewX = Math.max(m_viewX, m_lowerBound.x); m_viewX = Math.min(m_viewX, m_upperBound.x); m_viewY = Math.max(m_viewY, m_lowerBound.y); m_viewY = Math.min(m_viewY, m_upperBound.y); }; m_renderer.moveTo(m_viewX, m_viewY); } public function setBounds(a_x:Number, a_y:Number, a_width:Number, a_height:Number):void{ m_lowerBound.x = (a_x + (m_renderer.renderWidth / 2)); m_lowerBound.y = (a_y + (m_renderer.renderHeight / 2)); m_upperBound.x = ((a_x + a_width) - (m_renderer.renderWidth / 2)); m_upperBound.y = ((a_y + a_height) - (m_renderer.renderHeight / 2)); } public function get tensionX():Number{ return (m_tensionX); } public function get tensionY():Number{ return (m_tensionY); } public function shakeView(a_shakeTime:Number, a_shakeSize:Number):void{ m_shakeViewTimer = a_shakeTime; m_shakeSize = a_shakeSize; } public function set targetX(value:Number):void{ m_targetX = value; } public function get maxSeparationY():Number{ return (m_maxSeparationY); } public function set targetY(value:Number):void{ m_targetY = value; } public function get viewX():Number{ return (m_viewX); } public function get viewY():Number{ return (m_viewY); } public function get maxSeparationX():Number{ return (m_maxSeparationX); } public function set speedX(value:Number):void{ m_speedX = value; } public function set speedY(value:Number):void{ m_speedY = value; } public function get targetX():Number{ return (m_targetX); } public function get targetY():Number{ return (m_targetY); } public function isAtTarget():Boolean{ return ((((Math.abs((m_viewX - m_targetX)) < 0.01)) && ((Math.abs((m_viewY - m_targetY)) < 0.01)))); } public function get speedX():Number{ return (m_speedX); } public function get speedY():Number{ return (m_speedY); } public function clearTemporaryBounds():void{ m_temporaryLowerBound = null; m_temporaryUpperBound = null; } } }//package com.urbansquall.prophet.display
Section 123
//Behavior (com.urbansquall.prophet.engine.Behavior) package com.urbansquall.prophet.engine { import com.urbansquall.prophet.utils.*; import flash.utils.*; public class Behavior { public var entity:Entity; public var name:String; public function Behavior(a_entity:Entity, a_name:String, a_data:KeyValueMap=null){ super(); entity = a_entity; name = a_name; if (a_data != null){ loadData(a_data); }; } public function removingBehavior(a_behavior:Behavior):void{ } public function enable():void{ } public function postTick():void{ } public function disable():void{ } public function extendEntity():void{ } public function createShapes():Array{ return (null); } private function loadData(a_data:KeyValueMap):void{ var key:String; var a_data = a_data; var dictionary:Dictionary = a_data.dictionary; for (key in dictionary) { if (key == "name"){ throw (new Error("Behavior data can't have a property with the name 'name'")); }; if (key == "entity"){ throw (new Error("Behavior data can't have a property with the name 'name'")); }; this[key] = dictionary[key]; //unresolved jump var _slot1 = e; trace(((("Behavior data error. Could not find property [" + key) + "] for ") + this)); }; } public function addingBehavior(a_behavior:Behavior):void{ } public function tick(a_deltaTime:Number):void{ } public function dispose():void{ throw (new Error("Override Behavior.dispose")); } } }//package com.urbansquall.prophet.engine
Section 124
//Engine (com.urbansquall.prophet.engine.Engine) package com.urbansquall.prophet.engine { import flash.events.*; import flash.display.*; import com.urbansquall.prophet.display.*; import caurina.transitions.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.input.*; import flash.utils.*; import Box2D.Dynamics.*; public class Engine extends EventDispatcher { private var m_keyboardTemplate:KeyboardTemplate; private var m_keyboardState:KeyboardState; private var m_ticker:Ticker; private var m_dynamics:Dynamics; private var m_paused:Boolean;// = true private var m_accruedTime:Number; private var m_editorMode:Boolean; private var m_renderer:EngineRenderer; private var m_entityPruner:EntityPruner;// = null private var m_gameDef:GameDefinition; private var m_allowPruning:Boolean;// = true private var m_levelDef:LevelDefinition; private var m_entityManager:EntityManager; public function Engine(a_renderer:EngineRenderer, a_keyboardTemplate:KeyboardTemplate, a_allowPruning:Boolean, a_editorMode:Boolean){ super(); m_editorMode = a_editorMode; m_renderer = a_renderer; m_keyboardTemplate = a_keyboardTemplate; m_entityManager = new EntityManager(); m_entityManager.addEventListener(EngineEvent.DESTROY_ENTITY, cleanup, false, 0, true); m_accruedTime = 0; m_allowPruning = a_allowPruning; if (m_allowPruning){ m_entityPruner = new EntityPruner(m_renderer, this); }; } public function lookupEntity(a_id:String):Entity{ return (m_entityManager.lookupEntity(a_id)); } public function forcePrune():void{ m_entityPruner.tick(0); } public function isPaused():Boolean{ return (m_paused); } public function getDynamics():Dynamics{ return (m_dynamics); } public function destroyEntity(a_id:String):void{ var entity:Entity = m_entityManager.lookupEntity(a_id); if (entity == null){ return; }; m_entityManager.removeEntity(entity); } public function initialize(a_gameDef:GameDefinition):void{ m_gameDef = a_gameDef; dispatchEvent(new EngineEvent(EngineEvent.INITIALIZED)); } public function lookupEntityTypeDefinition(a_type:String):EntityTypeDefinition{ return (m_gameDef.lookupEntityType(a_type)); } public function getEntityManager():EntityManager{ return (m_entityManager); } public function save():LevelDefinition{ var key:String; var levelGraphic:LevelGraphicDefinition; var entity:Entity; var state:LevelDefinition = new LevelDefinition(); state.setGravity(m_levelDef.gravityX, m_levelDef.gravityY); state.setWorldBounds(m_levelDef.worldBoundX, m_levelDef.worldBoundY, m_levelDef.worldBoundWidth, m_levelDef.worldBoundHeight); state.setAllowSleep(m_levelDef.allowSleep); var levelGraphics:Array = m_levelDef.getLevelGraphics(); var g:int; while (g < levelGraphics.length) { levelGraphic = levelGraphics[g]; state.addLevelGraphic(levelGraphic); g++; }; var e:int; while (e < m_entityManager.numEntities) { entity = m_entityManager.getEntityAt(e); if (m_entityManager.lookupEntity(entity.id) == null){ } else { state.addSpawnInfo(entity.createSpawnInfo()); }; e++; }; var propertyDictionary:Dictionary = m_levelDef.getDataDump().dictionary; for (key in propertyDictionary) { state.getDataDump().setString(key, propertyDictionary[key]); }; return (state); } public function get accruedTime():Number{ return (m_accruedTime); } private function handleBodyHitWorldBoundary(a_event:HitWorldBoundaryEvent):void{ var entity:Entity = (a_event.body.GetUserData() as Entity); if (entity == null){ return; }; trace(("Boundary violation " + entity)); destroyEntity(entity.id); } public function tick(a_interval:Number):void{ if (m_paused){ return; }; m_accruedTime = (m_accruedTime + a_interval); m_entityManager.tick(a_interval); m_dynamics.step(a_interval); m_renderer.tick(a_interval); if (m_allowPruning){ m_entityPruner.tick(a_interval); }; dispatchEvent(new UpdateEvent(a_interval)); m_keyboardState.tick(); } public function dispose():void{ clear(); } private function cleanup(a_destroyEntityEvent:DestroyEntityEvent):void{ var graphic:Graphic; var entity:Entity = a_destroyEntityEvent.entity; var g:int = (entity.graphics.length - 1); while (g >= 0) { graphic = entity.graphics[g]; graphic.display.parent.removeChild(graphic.display); g--; }; m_dynamics.destroyBody(entity.body); entity.dispose(); } public function addEntityType(a_entityDef:EntityTypeDefinition):void{ m_gameDef.registerEntityType(a_entityDef); } public function get renderer():EngineRenderer{ return (m_renderer); } public function clear():void{ var entity:Entity; var g:int; var graphic:Graphic; m_accruedTime = 0; m_keyboardState.dispose(); m_keyboardState = null; m_renderer.clear(); var i:int = (m_entityManager.numEntities - 1); while (i >= 0) { entity = (m_entityManager.getEntityAt(i) as Entity); g = (entity.graphics.length - 1); while (g >= 0) { graphic = entity.graphics[g]; if (graphic.display.parent != null){ graphic.display.parent.removeChild(graphic.display); } else { trace((((((("Entity graphic [" + graphic.name) + "] on [") + entity.id) + "] of type [") + entity.entityTypeDefinition.type) + "] was orphaned.")); }; g--; }; m_dynamics.destroyBody(entity.body); i--; }; m_entityManager.dispose(); m_entityManager = new EntityManager(); m_entityManager.addEventListener(EngineEvent.DESTROY_ENTITY, cleanup, false, 0, true); if (m_allowPruning){ m_entityPruner = new EntityPruner(m_renderer, this); }; m_dynamics.dispose(); m_dynamics = null; m_ticker.stop(); m_ticker = null; } private function processTickEvent(a_tickEvent:TickerEvent):void{ tick(a_tickEvent.interval); } private function createEntityFromTypeDefinition(a_spawnInfo:EntitySpawnInfo, a_typeDefinition:EntityTypeDefinition):Entity{ var graphicDef:GraphicDefinition; var graphic:Graphic; var g:int; var behaviorDefinition:BehaviorDefinition; var behaviorClass:Class; var entityBehavior:Behavior; var behaviorShapes:Array; if (a_spawnInfo.id == ""){ a_spawnInfo.id = ("id" + Math.random()); }; var id:String = a_spawnInfo.id; var entityTypeDef:EntityTypeDefinition = a_typeDefinition; var entity:Entity = new Entity(id, a_spawnInfo, this, entityTypeDef); var behaviorCount:int = entityTypeDef.behaviors.length; var additionalShapes:Array = []; var i:int; while (i < behaviorCount) { behaviorDefinition = entityTypeDef.behaviors[i]; behaviorClass = behaviorDefinition.type; entityBehavior = new behaviorClass(entity, behaviorDefinition.name, behaviorDefinition.data); entityBehavior.extendEntity(); behaviorShapes = entityBehavior.createShapes(); if (behaviorShapes != null){ additionalShapes = additionalShapes.concat(behaviorShapes); }; entity.addBehavior(entityBehavior); i++; }; var shapes:Array = additionalShapes.concat(entityTypeDef.shapes); entity.body = m_dynamics.createBody(entityTypeDef.physics, entityTypeDef.fixed, shapes, a_spawnInfo.x, a_spawnInfo.y, a_spawnInfo.vx, a_spawnInfo.vy, a_spawnInfo.rotation, a_spawnInfo.scale); entity.body.SetUserData(entity); g = 0; while (g < entityTypeDef.graphics.length) { graphicDef = entityTypeDef.graphics[g]; graphic = graphicDef.createGraphic(a_spawnInfo.scale); m_renderer.addDisplayObject(graphic.display, graphicDef.renderLayer); entity.addGraphic(graphic); g++; }; if (m_editorMode){ g = 0; while (g < entityTypeDef.editorGraphics.length) { graphicDef = entityTypeDef.editorGraphics[g]; graphic = graphicDef.createGraphic(a_spawnInfo.scale); m_renderer.addDisplayObject(graphic.display, graphicDef.renderLayer); entity.addGraphic(graphic); g++; }; }; entity.updateGraphics(0); m_entityManager.addEntity(entity); return (entity); } public function start():void{ m_paused = false; m_ticker = new Ticker(33); m_ticker.addEventListener(TickerEvent.TICK, processTickEvent); m_ticker.start(); m_keyboardState = new KeyboardState(m_renderer.renderContainer.stage, m_keyboardTemplate); m_renderer.renderContainer.stage.focus = m_renderer.renderContainer.stage; } public function queryBox(a_x:Number, a_y:Number, a_width:Number, a_height:Number, includeStatic:Boolean=false, a_allowSensors:Boolean=false):Array{ var entity:Entity; var debugDraw:Sprite; var box:Sprite; var result:Array = m_dynamics.getBodiesInBox(a_x, a_y, a_width, a_height, includeStatic, a_allowSensors); var entities:Array = []; var i:int; while (i < result.length) { entity = (result[i].GetUserData() as Entity); if (entity != null){ if (entities.indexOf(entity) < 0){ entities.push(entity); }; }; i++; }; if (m_renderer.debugDraw.drawQueries){ debugDraw = m_renderer.lookupRenderLayer(EngineRenderer.DEBUG_LAYER); box = new Sprite(); box.graphics.lineStyle(2, 0xFF, 0.8); box.graphics.beginFill(0xFF, 0.5); box.x = a_x; box.y = a_y; box.graphics.drawRect(0, 0, a_width, a_height); debugDraw.addChild(box); Tweener.addTween(box, {alpha:0, time:0.5, onComplete:debugDraw.removeChild, onCompleteParams:[box]}); }; return (entities); } public function pickEntity(a_pickX:Number, a_pickY:Number, includeStatic:Boolean=false, a_ignoredEnemies:Array=null):Entity{ var entity:Entity; var i:int; var ignoredBodies:Array; if (((!((a_ignoredEnemies == null))) && ((a_ignoredEnemies.length > 0)))){ ignoredBodies = []; i = 0; while (i < a_ignoredEnemies.length) { entity = a_ignoredEnemies[i]; ignoredBodies.push(entity.body); i++; }; }; var body:b2Body = m_dynamics.getBodyAtPoint(a_pickX, a_pickY, includeStatic, ignoredBodies); if (body == null){ return (null); }; entity = (body.GetUserData() as Entity); return (entity); } public function load(a_levelDef:LevelDefinition):void{ var bounds:Sprite; var levelGraphic:LevelGraphicDefinition; var graphic:Graphic; var spawnInfo:EntitySpawnInfo; m_levelDef = a_levelDef; var debugDraw:Sprite; if (m_renderer.debugDraw.drawLevelBoundaries){ debugDraw = m_renderer.lookupRenderLayer(EngineRenderer.DEBUG_LAYER); bounds = new Sprite(); bounds.graphics.lineStyle(5, 0xFF0000, 0.5); bounds.graphics.drawRect(a_levelDef.worldBoundX, a_levelDef.worldBoundY, a_levelDef.worldBoundWidth, a_levelDef.worldBoundHeight); debugDraw.addChild(bounds); }; if (m_renderer.debugDraw.drawPhysicsShapes){ if (debugDraw == null){ debugDraw = m_renderer.lookupRenderLayer(EngineRenderer.DEBUG_LAYER); }; } else { debugDraw = null; }; m_dynamics = new Dynamics(debugDraw); m_dynamics.addEventListener(HitWorldBoundaryEvent.HIT_WORLD_BOUNDARY, handleBodyHitWorldBoundary, false, 0, true); m_dynamics.create(m_levelDef); var levelGraphics:Array = m_levelDef.getLevelGraphics(); var g:int; while (g < levelGraphics.length) { levelGraphic = levelGraphics[g]; graphic = levelGraphic.graphicDef.createGraphic(1); graphic.display.x = levelGraphic.x; graphic.display.y = levelGraphic.y; renderer.addDisplayObject(graphic.display, levelGraphic.graphicDef.renderLayer); g++; }; var spawnInfos:Array = m_levelDef.getSpawnInfos(); var i:int; while (i < spawnInfos.length) { spawnInfo = spawnInfos[i]; createEntity(spawnInfo); i++; }; m_entityManager.tick(0); dispatchEvent(new EngineEvent(EngineEvent.LOAD)); } public function removeEntityType(a_type:String):void{ m_gameDef.removeEntityType(a_type); } public function get keyboardState():KeyboardState{ return (m_keyboardState); } public function pause():void{ m_paused = true; } public function getEntitiesWithType(a_type:String):Array{ var entity:Entity; var results:Array = []; var i:int = (m_entityManager.numEntities - 1); while (i >= 0) { entity = (m_entityManager.getEntityAt(i) as Entity); if (entity.entityTypeDefinition.type == a_type){ results.push(entity); }; i--; }; return (results); } public function unpause():void{ m_paused = false; } public function createEntity(a_spawnInfo:EntitySpawnInfo):Entity{ var entityTypeDef:EntityTypeDefinition = m_gameDef.lookupEntityType(a_spawnInfo.type); if (entityTypeDef == null){ throw (new Error((("There is no entity definition with type [" + a_spawnInfo.type) + "]"))); }; return (createEntityFromTypeDefinition(a_spawnInfo, entityTypeDef)); } } }//package com.urbansquall.prophet.engine
Section 125
//EngineEvent (com.urbansquall.prophet.engine.EngineEvent) package com.urbansquall.prophet.engine { import flash.events.*; public class EngineEvent extends Event { public static const PRUNE_EVENT:String = "ee_prn"; public static const LOAD:String = "ee_load"; public static const SPAWN_ENTITY:String = "ee_e_spawn"; public static const BEGIN_TOUCH:String = "*bt"; public static const END_TOUCH:String = ")et"; public static const UPDATE:String = "ee_update"; public static const INITIALIZED:String = "ee_init"; public static const DESTROY_ENTITY:String = "ee_e_des"; public static const PERSIST_TOUCH:String = "(pt"; public function EngineEvent(a_type:String){ super(a_type); } } }//package com.urbansquall.prophet.engine
Section 126
//Entity (com.urbansquall.prophet.engine.Entity) package com.urbansquall.prophet.engine { import flash.events.*; import flash.display.*; import flash.geom.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Dynamics.Joints.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; public class Entity extends EventDispatcher { private var m_entityTypeDefinition:EntityTypeDefinition; public var graphics:Array; private var m_behaviors:Array; private var m_areGraphicsFlipped:Boolean;// = false public var body:b2Body;// = null private var m_id:String; private var m_pruneType:String; public var properties:KeyValueMap; private var m_joints:Array; private var m_engine:Engine; private var m_spawnInfo:EntitySpawnInfo; public function Entity(a_id:String, a_spawnInfo:EntitySpawnInfo, a_engine:Engine, a_entityTypeDefinition:EntityTypeDefinition){ graphics = []; m_behaviors = []; m_joints = []; super(); m_id = a_id; m_spawnInfo = a_spawnInfo; m_engine = a_engine; if (a_spawnInfo.pruneType == PruneType.INHERIT){ m_pruneType = a_entityTypeDefinition.pruneType; } else { m_pruneType = a_spawnInfo.pruneType; }; properties = a_entityTypeDefinition.properties.clone(); m_entityTypeDefinition = a_entityTypeDefinition; properties = a_entityTypeDefinition.properties.clone(); properties.integrate(a_spawnInfo.properties.dictionary); } public function get pruneType():String{ return (m_pruneType); } public function addGraphic(a_graphic:Graphic):void{ graphics.push(a_graphic); } public function get flipped():Boolean{ return (m_areGraphicsFlipped); } public function lookupGraphic(a_name:String):Graphic{ var graphic:Graphic; var g:int; while (g < graphics.length) { graphic = graphics[g]; if (graphic.name == a_name){ return (graphic); }; g++; }; return (null); } public function addBehavior(a_behavior:Behavior):void{ var behavior:Behavior; var b:int; while (b < m_behaviors.length) { behavior = m_behaviors[b]; behavior.addingBehavior(a_behavior); b++; }; m_behaviors.push(a_behavior); } public function get id():String{ return (m_id); } public function tick(a_deltaTime:Number):void{ var behavior:Behavior; updateGraphics(a_deltaTime); var b:int; while (b < m_behaviors.length) { behavior = m_behaviors[b]; behavior.tick(a_deltaTime); b++; }; } public function getPosition():Point{ var position:Point = new Point((body.GetPosition().x * Dynamics.INVERSE_SCALE), (body.GetPosition().y * Dynamics.INVERSE_SCALE)); return (position); } public function applyForce(a_fx:Number, a_fy:Number):void{ body.ApplyForce(new b2Vec2((Dynamics.INVERSE_SCALE * a_fx), (Dynamics.INVERSE_SCALE * a_fy)), body.GetPosition()); } public function getJoints():Array{ return (m_joints); } public function applyImpulse(a_fx:Number, a_fy:Number):void{ body.ApplyImpulse(new b2Vec2((Dynamics.INVERSE_SCALE * a_fx), (Dynamics.INVERSE_SCALE * a_fy)), body.GetPosition()); } public function setPosition(a_px:Number, a_py:Number):void{ body.SetXForm(new b2Vec2((Dynamics.SCALE * a_px), (Dynamics.SCALE * a_py)), body.GetAngle()); } public function dispose():void{ var behavior:Behavior; var b:int = (m_behaviors.length - 1); while (b >= 0) { behavior = m_behaviors[b]; behavior.dispose(); b--; }; body = null; m_engine = null; graphics.splice(0); graphics = null; properties = null; m_behaviors.splice(0); m_behaviors = null; } public function destroyJoint(a_joint:b2Joint):void{ if (m_joints.indexOf(a_joint) >= 0){ m_engine.getDynamics().destroyJoint(a_joint); m_joints.splice(m_joints.indexOf(a_joint), 1); }; } public function createSpawnInfo():EntitySpawnInfo{ var spawnInfo:EntitySpawnInfo = m_spawnInfo.clone(); if (body != null){ spawnInfo.vx = getVelocity().x; spawnInfo.vy = getVelocity().y; spawnInfo.x = getPosition().x; spawnInfo.y = getPosition().y; spawnInfo.rotation = getRotation(); }; spawnInfo.properties = properties.clone(); return (spawnInfo); } public function getSpawnInfo():EntitySpawnInfo{ return (m_spawnInfo); } public function getEngine():Engine{ return (m_engine); } public function get type():String{ return (m_entityTypeDefinition.type); } public function removeGraphic(a_name:String):void{ var graphic:Graphic; var g:int; while (g < graphics.length) { graphic = graphics[g]; if (graphic.name == a_name){ m_engine.renderer.removeDisplayObject(graphic.display); graphics.splice(g, 1); return; }; g++; }; } public function killBehavior(a_name:String):void{ var behavior:Behavior = lookupBehavior(a_name); if (behavior == null){ return; }; behavior.dispose(); m_behaviors.splice(m_behaviors.indexOf(behavior), 1); } public function getVelocity():Point{ var velocity:Point = new Point((body.GetLinearVelocity().x * Dynamics.INVERSE_SCALE), (body.GetLinearVelocity().y * Dynamics.INVERSE_SCALE)); return (velocity); } public function postTick():void{ var behavior:Behavior; var b:int; while (b < m_behaviors.length) { behavior = m_behaviors[b]; behavior.postTick(); b++; }; } public function setVelocity(a_vx:Number, a_vy:Number):void{ body.SetLinearVelocity(new b2Vec2((Dynamics.SCALE * a_vx), (Dynamics.SCALE * a_vy))); } public function set flip(a_value:Boolean):void{ var graphic:Graphic; var display:DisplayObject; m_areGraphicsFlipped = a_value; var g:int; while (g < graphics.length) { graphic = graphics[g]; display = graphic.display; if (m_areGraphicsFlipped){ display.scaleX = -1; } else { display.scaleX = 1; }; g++; }; } public function lookupBehavior(a_name:String):Behavior{ var behavior:Behavior; var b:int; while (b < m_behaviors.length) { behavior = m_behaviors[b]; if (behavior.name == a_name){ return (behavior); }; b++; }; return (null); } public function get entityTypeDefinition():EntityTypeDefinition{ return (m_entityTypeDefinition); } override public function toString():String{ var result:String = ((("[Entity:" + id) + ",") + entityTypeDefinition.type); if (body != null){ result = (result + ((("," + getPosition().x) + ",") + getPosition().y)); }; result = (result + "]"); return (result); } public function getRotation():Number{ return ((body.GetAngle() / 0.0174532925)); } public function createPrismaticJoint(a_attachee:Entity, a_axisX:Number, a_axisY:Number, a_anchor:Point=null, a_lowerTranslation:Number=0, a_upperTranslation:Number=5):void{ if (a_anchor == null){ a_anchor = new Point(); a_anchor.x = this.body.GetPosition().x; a_anchor.y = this.body.GetPosition().y; }; a_anchor.x = (a_anchor.x * Dynamics.SCALE); a_anchor.y = (a_anchor.y * Dynamics.SCALE); var jointDef:b2PrismaticJointDef = new b2PrismaticJointDef(); var worldAxis:b2Vec2 = new b2Vec2(a_axisX, a_axisY); jointDef.Initialize(this.body, a_attachee.body, new b2Vec2(a_anchor.x, a_anchor.y), worldAxis); jointDef.lowerTranslation = (a_lowerTranslation * Dynamics.SCALE); jointDef.upperTranslation = (a_upperTranslation * Dynamics.SCALE); jointDef.enableLimit = true; var dynamics:Dynamics = m_engine.getDynamics(); var joint:b2Joint = dynamics.createJoint(jointDef); m_joints.push(joint); } public function createDistanceJoint(a_attachee:Entity, a_myAnchor:Point=null, a_theirAnchor:Point=null):void{ if (a_myAnchor == null){ a_myAnchor = new Point(); a_myAnchor.x = this.body.GetPosition().x; a_myAnchor.y = this.body.GetPosition().y; }; a_myAnchor.x = (a_myAnchor.x * Dynamics.SCALE); a_myAnchor.y = (a_myAnchor.y * Dynamics.SCALE); if (a_theirAnchor == null){ a_theirAnchor = new Point(); a_theirAnchor.x = a_attachee.body.GetPosition().x; a_theirAnchor.y = a_attachee.body.GetPosition().y; }; a_theirAnchor.x = (a_theirAnchor.x * Dynamics.SCALE); a_theirAnchor.y = (a_theirAnchor.y * Dynamics.SCALE); var jointDef:b2DistanceJointDef = new b2DistanceJointDef(); jointDef.Initialize(this.body, a_attachee.body, new b2Vec2(a_myAnchor.x, a_myAnchor.y), new b2Vec2(a_theirAnchor.x, a_theirAnchor.y)); jointDef.frequencyHz = 500000; jointDef.dampingRatio = 0.95; jointDef.collideConnected = false; var dynamics:Dynamics = m_engine.getDynamics(); var joint:b2Joint = dynamics.createJoint(jointDef); m_joints.push(joint); } public function updateGraphics(a_deltaTime:Number):void{ var graphic:Graphic; var display:DisplayObject; if (body == null){ return; }; var position:b2Vec2 = body.GetPosition(); var gx:Number = Math.round((position.x * Dynamics.INVERSE_SCALE)); var gy:Number = Math.round((position.y * Dynamics.INVERSE_SCALE)); var rotation:Number = Math.round((body.GetAngle() * 57.2957795)); var g:int; while (g < graphics.length) { graphic = graphics[g]; graphic.update(a_deltaTime); display = graphic.display; display.x = gx; display.y = gy; if (graphic.rotates){ display.rotation = rotation; }; g++; }; } public function removeBehavior(a_behavior:Behavior):void{ var behavior:Behavior; var b:int; while (b < m_behaviors.length) { behavior = m_behaviors[b]; if (behavior == a_behavior){ } else { behavior.removingBehavior(a_behavior); }; b++; }; m_behaviors.splice(m_behaviors.indexOf(a_behavior), 1); } } }//package com.urbansquall.prophet.engine
Section 127
//EntityManager (com.urbansquall.prophet.engine.EntityManager) package com.urbansquall.prophet.engine { import flash.events.*; import com.urbansquall.prophet.events.*; import flash.utils.*; public class EntityManager extends EventDispatcher { private var m_entitiesToBeAdded:Array; private var m_entitiesToBeRemoved:Array; private var m_entities:Array; private var m_idMap:Dictionary; public function EntityManager(){ super(); m_entities = new Array(); m_idMap = new Dictionary(); m_entitiesToBeAdded = new Array(); m_entitiesToBeRemoved = new Array(); } private function addNewEntities(a_cleaningUp:Boolean):void{ var entity:Entity; var entityCount:int = m_entitiesToBeAdded.length; var entityIndex:int = (entityCount - 1); while (entityIndex >= 0) { entity = m_entitiesToBeAdded[entityIndex]; m_entities.push(entity); entityIndex--; }; m_entitiesToBeAdded.splice(0); } public function addEntity(a_entity:Entity):void{ var entity:Entity; if (m_entitiesToBeAdded.indexOf(a_entity) != -1){ throw (new Error("EntityManager:addEntity. This entity is already queued for addition.")); }; if (m_idMap[a_entity.id] != null){ throw (new Error((("EntityManager:addEntity. There is an entity with id [" + a_entity.id) + "] already. Ensure ids are unique."))); }; var entityCount:int = m_entitiesToBeAdded.length; var entityIndex:int = (entityCount - 1); while (entityIndex >= 0) { entity = m_entitiesToBeAdded[entityIndex]; if (entity.id == a_entity.id){ throw (new Error((("EntityManager:addEntity. There is an entity with id [" + a_entity.id) + "] already. Ensure ids are unique."))); }; entityIndex--; }; m_entitiesToBeAdded.push(a_entity); m_idMap[a_entity.id] = a_entity; } public function removeEntity(a_entity:Entity):void{ if (m_entitiesToBeRemoved.indexOf(a_entity) != -1){ return; }; if (m_idMap[a_entity.id] == null){ return; }; delete m_idMap[a_entity.id]; m_entitiesToBeRemoved.push(a_entity); } private function processAddAndRemoves(a_cleaningUp:Boolean=false):void{ addNewEntities(a_cleaningUp); removeOldEntities(a_cleaningUp); } private function removeOldEntities(a_cleaningUp:Boolean):void{ var entity:Entity; var removalIndex:int; var entityCount:int = m_entitiesToBeRemoved.length; var entityIndex:int = (entityCount - 1); while (entityIndex >= 0) { entity = m_entitiesToBeRemoved[entityIndex]; removalIndex = m_entities.indexOf(entity); if (removalIndex >= 0){ m_entities.splice(removalIndex, 1); if (!a_cleaningUp){ dispatchEvent(new DestroyEntityEvent(entity)); }; }; entityIndex--; }; m_entitiesToBeRemoved.splice(0); } public function getEntityAt(a_index:int):Entity{ return (m_entities[a_index]); } public function get numEntities():int{ return (m_entities.length); } public function tick(a_deltaTime:Number):void{ var entity:Entity; var entityIndex:int; var entityCount:int = m_entities.length; entityIndex = (entityCount - 1); while (entityIndex >= 0) { entity = m_entities[entityIndex]; entity.tick(a_deltaTime); entityIndex--; }; entityIndex = (entityCount - 1); while (entityIndex >= 0) { entity = m_entities[entityIndex]; entity.postTick(); entityIndex--; }; processAddAndRemoves(); } override public function toString():String{ return (m_entities.join("&")); } public function lookupEntity(a_id:String):Entity{ return (m_idMap[a_id]); } public function dispose():void{ var entity:Entity; if (m_entities == null){ return; }; processAddAndRemoves(true); var entityCount:int = m_entities.length; var entityIndex:int = (entityCount - 1); while (entityIndex >= 0) { entity = m_entities[entityIndex]; delete m_idMap[entity.id]; entity.dispose(); entityIndex--; }; m_entities.splice(0); m_entities = null; m_entitiesToBeAdded = null; m_entitiesToBeRemoved = null; m_idMap = null; } } }//package com.urbansquall.prophet.engine
Section 128
//EntityPruner (com.urbansquall.prophet.engine.EntityPruner) package com.urbansquall.prophet.engine { import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.events.*; import flash.utils.*; public class EntityPruner { private var m_activeRow:int; private var m_oldPruneRow:int;// = 0 private var m_activeCol:int; private var m_oldPruneCol:int;// = 0 private var m_prunedEntityMap:Dictionary; private var m_engine:Engine; private var m_renderer:EngineRenderer; private var m_entityManager:EntityManager; private var m_view:View; public function EntityPruner(a_renderer:EngineRenderer, a_engine:Engine){ super(); m_renderer = a_renderer; m_engine = a_engine; m_entityManager = m_engine.getEntityManager(); m_view = m_renderer.view; m_prunedEntityMap = new Dictionary(); } public function getPruneTileColumn(a_locationX:Number):int{ return (Math.floor((a_locationX / m_renderer.renderWidth))); } public function getPrunedEntityListAtPruneTile(a_pruneCol:int, a_pruneRow:int):Array{ var list:Array = m_prunedEntityMap[((a_pruneCol + "_") + a_pruneRow)]; if (list == null){ list = new Array(); m_prunedEntityMap[((a_pruneCol + "_") + a_pruneRow)] = list; }; return (list); } public function tick(a_interval:Number):void{ var entityCol:int; var entityRow:int; var prunedEntity:EntitySpawnInfo; var prunedList:Array; var e:int; var entity:Entity; var c:int; var r:int; var p:int; var newCol:int = getPruneTileColumn((m_view.viewX + (m_renderer.renderWidth / 2))); var newRow:int = getPruneTileRow((m_view.viewY + (m_renderer.renderHeight / 2))); e = (m_entityManager.numEntities - 1); while (e >= 0) { entity = m_entityManager.getEntityAt(e); if (entity.pruneType == PruneType.IMMUNE){ } else { entityCol = getPruneTileColumn(entity.getPosition().x); entityRow = getPruneTileRow(entity.getPosition().y); if ((((((((entityCol < (newCol - 1))) || ((entityCol > (newCol + 1))))) || ((entityRow < (newRow - 1))))) || ((entityRow > (newRow + 1))))){ if (entity.hasEventListener(EngineEvent.PRUNE_EVENT)){ entity.dispatchEvent(new PruneEvent()); }; switch (entity.pruneType){ case PruneType.DIE: m_engine.destroyEntity(entity.id); break; case PruneType.NORMAL: prunedEntity = entity.createSpawnInfo(); prunedList = getPrunedEntityListAtPruneTile(entityCol, entityRow); prunedList.push(prunedEntity); m_engine.destroyEntity(entity.id); break; case PruneType.RESPAWN: prunedEntity = entity.getSpawnInfo().clone(); prunedList = getPrunedEntityListAtPruneTile(entityCol, entityRow); prunedList.push(prunedEntity); m_engine.destroyEntity(entity.id); break; }; }; }; e--; }; if (((!((newCol == m_oldPruneCol))) || (!((newRow == m_oldPruneRow))))){ c = (newCol - 1); while (c < (newCol + 1)) { r = (newRow - 1); while (r < (newRow + 1)) { prunedList = getPrunedEntityListAtPruneTile(c, r); p = 0; while (p < prunedList.length) { prunedEntity = prunedList[p]; m_engine.createEntity(prunedEntity); p++; }; prunedList.splice(0); r++; }; c++; }; m_oldPruneCol = newCol; m_oldPruneRow = newRow; }; } public function getPruneTileRow(a_locationY:Number):int{ return (Math.floor((a_locationY / m_renderer.renderHeight))); } } }//package com.urbansquall.prophet.engine
Section 129
//EntitySpawnInfo (com.urbansquall.prophet.engine.EntitySpawnInfo) package com.urbansquall.prophet.engine { import com.urbansquall.prophet.utils.*; public class EntitySpawnInfo { public var vx:Number; public var vy:Number; public var scale:Number; public var pruneType:String; public var properties:KeyValueMap; public var x:Number; public var y:Number; public var type:String; public var id:String; public var rotation:Number; public function EntitySpawnInfo(a_type:String, a_id:String, a_x:Number, a_y:Number, a_vx:Number=0, a_vy:Number=0, a_rotation:Number=0, a_scale:Number=1, a_properties:KeyValueMap=null, a_pruneType:String="inherit"){ super(); type = a_type; id = a_id; x = a_x; y = a_y; vx = a_vx; vy = a_vy; scale = a_scale; rotation = a_rotation; pruneType = a_pruneType; properties = a_properties; if (properties == null){ properties = new KeyValueMap(); }; } public function toString():String{ return ((((("<EntitySpawnInfo t:" + type) + " id:") + id) + ">")); } public function clone():EntitySpawnInfo{ return (new EntitySpawnInfo(type, id, x, y, vx, vy, rotation, scale, properties.clone(), pruneType)); } } }//package com.urbansquall.prophet.engine
Section 130
//GingerGraphic (com.urbansquall.prophet.engine.GingerGraphic) package com.urbansquall.prophet.engine { import com.urbansquall.ginger.*; public class GingerGraphic extends Graphic { public var animationPlayer:AnimationPlayer; public function GingerGraphic(a_animationPlayer:AnimationPlayer, a_name:String){ super(a_animationPlayer, a_name); animationPlayer = a_animationPlayer; } override public function update(a_deltaTime:Number):void{ animationPlayer.update(a_deltaTime); } override public function toString():String{ return ((("<GingerGraphic:" + name) + ">")); } } }//package com.urbansquall.prophet.engine
Section 131
//Graphic (com.urbansquall.prophet.engine.Graphic) package com.urbansquall.prophet.engine { import flash.display.*; public class Graphic { public var display:DisplayObject; public var rotates:Boolean; public var name:String; public function Graphic(a_display:DisplayObject, a_name:String){ super(); display = a_display; name = a_name; rotates = true; } public function update(a_deltaTime:Number):void{ } public function toString():String{ return ((("<Graphic:" + name) + ">")); } } }//package com.urbansquall.prophet.engine
Section 132
//PruneType (com.urbansquall.prophet.engine.PruneType) package com.urbansquall.prophet.engine { public class PruneType { public static const DIE:String = "die"; public static const IMMUNE:String = "immune"; public static const NORMAL:String = "normal"; public static const RESPAWN:String = "respawn"; public static const INHERIT:String = "inherit"; public function PruneType(){ super(); } } }//package com.urbansquall.prophet.engine
Section 133
//SafeSol (com.urbansquall.prophet.engine.SafeSol) package com.urbansquall.prophet.engine { import com.urbansquall.security.*; public class SafeSol extends SafeSolManager { private static var s_instance:SafeSol = null; public function SafeSol(a_appName:String, a_hexKey:uint){ super(a_appName, a_hexKey); if (s_instance != null){ throw (new Error("Can't instantiate two SafeSols")); }; s_instance = this; } public static function get instance():SafeSol{ return (s_instance); } } }//package com.urbansquall.prophet.engine
Section 134
//Ticker (com.urbansquall.prophet.engine.Ticker) package com.urbansquall.prophet.engine { import flash.events.*; import flash.display.*; import flash.utils.*; public class Ticker extends EventDispatcher { private var m_accruedTime:Number; private var m_running:Boolean; private var m_shape:Shape; private var m_delay:Number; private var m_timeOfLastUpdate:Number; public function Ticker(a_delay:Number=33){ super(); m_running = false; m_delay = a_delay; m_shape = new Shape(); } public function get delay():int{ return (m_delay); } public function stop():void{ m_shape.removeEventListener(Event.ENTER_FRAME, tick); m_running = false; } private function calculateDeltaTime():Number{ var currentTime:Number = getTimer(); var deltaTime:Number = (currentTime - m_timeOfLastUpdate); m_timeOfLastUpdate = currentTime; return (deltaTime); } public function start():void{ m_running = true; m_timeOfLastUpdate = getTimer(); m_accruedTime = 0; m_shape.addEventListener(Event.ENTER_FRAME, tick, false, 0, true); } private function tick(a_event:Event):void{ var deltaTime:Number = calculateDeltaTime(); if (!m_running){ return; }; m_accruedTime = (m_accruedTime + deltaTime); while (m_accruedTime >= m_delay) { m_accruedTime = (m_accruedTime - m_delay); dispatchEvent(new TickerEvent(m_delay)); }; } public function get running():Boolean{ return (m_running); } } }//package com.urbansquall.prophet.engine
Section 135
//TickerEvent (com.urbansquall.prophet.engine.TickerEvent) package com.urbansquall.prophet.engine { import flash.events.*; public class TickerEvent extends Event { private var m_interval:Number; public static const TICK:String = "tick"; public function TickerEvent(a_interval:Number){ super(TICK, false, false); m_interval = a_interval; } public function get interval():Number{ return (m_interval); } } }//package com.urbansquall.prophet.engine
Section 136
//BeginTouchEvent (com.urbansquall.prophet.events.BeginTouchEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class BeginTouchEvent extends TouchEvent { public function BeginTouchEvent(a_position:b2Vec2, a_normal:b2Vec2, a_velocity:b2Vec2, a_myShape:b2Shape, a_theirShape:b2Shape, a_myEntity:Entity, a_theirEntity:Entity){ super(EngineEvent.BEGIN_TOUCH, a_position, a_normal, a_velocity, a_myShape, a_theirShape, a_myEntity, a_theirEntity); } } }//package com.urbansquall.prophet.events
Section 137
//DestroyEntityEvent (com.urbansquall.prophet.events.DestroyEntityEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; public class DestroyEntityEvent extends EngineEvent { public var entity:Entity; public function DestroyEntityEvent(a_entity:Entity){ super(EngineEvent.DESTROY_ENTITY); entity = a_entity; } } }//package com.urbansquall.prophet.events
Section 138
//EndTouchEvent (com.urbansquall.prophet.events.EndTouchEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class EndTouchEvent extends TouchEvent { public function EndTouchEvent(a_position:b2Vec2, a_normal:b2Vec2, a_velocity:b2Vec2, a_myShape:b2Shape, a_theirShape:b2Shape, a_myEntity:Entity, a_theirEntity:Entity){ super(EngineEvent.END_TOUCH, a_position, a_normal, a_velocity, a_myShape, a_theirShape, a_myEntity, a_theirEntity); } } }//package com.urbansquall.prophet.events
Section 139
//PersistTouchEvent (com.urbansquall.prophet.events.PersistTouchEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class PersistTouchEvent extends TouchEvent { public function PersistTouchEvent(a_position:b2Vec2, a_normal:b2Vec2, a_velocity:b2Vec2, a_myShape:b2Shape, a_theirShape:b2Shape, a_myEntity:Entity, a_theirEntity:Entity){ super(EngineEvent.PERSIST_TOUCH, a_position, a_normal, a_velocity, a_myShape, a_theirShape, a_myEntity, a_theirEntity); } } }//package com.urbansquall.prophet.events
Section 140
//PruneEvent (com.urbansquall.prophet.events.PruneEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; public class PruneEvent extends EngineEvent { public function PruneEvent(){ super(EngineEvent.PRUNE_EVENT); } } }//package com.urbansquall.prophet.events
Section 141
//TouchEvent (com.urbansquall.prophet.events.TouchEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class TouchEvent extends EngineEvent { public var velocity:b2Vec2; public var theirShape:b2Shape; public var position:b2Vec2; public var myEntity:Entity; public var myShape:b2Shape; public var normal:b2Vec2; public var theirEntity:Entity; public function TouchEvent(a_type:String, a_position:b2Vec2, a_normal:b2Vec2, a_velocity:b2Vec2, a_myShape:b2Shape, a_theirShape:b2Shape, a_myEntity:Entity, a_theirEntity:Entity){ super(a_type); normal = a_normal; position = a_position; velocity = a_velocity; myShape = a_myShape; theirShape = a_theirShape; myEntity = a_myEntity; theirEntity = a_theirEntity; } } }//package com.urbansquall.prophet.events
Section 142
//UpdateEvent (com.urbansquall.prophet.events.UpdateEvent) package com.urbansquall.prophet.events { import com.urbansquall.prophet.engine.*; public class UpdateEvent extends EngineEvent { public var interval:Number; public function UpdateEvent(a_interval:Number){ super(EngineEvent.UPDATE); interval = a_interval; } } }//package com.urbansquall.prophet.events
Section 143
//KeyboardMap (com.urbansquall.prophet.input.KeyboardMap) package com.urbansquall.prophet.input { public class KeyboardMap { public static const Z:uint = 90; public static const KEYNAMES:Array = ["0", "1", "2", "3", "4", "5", "6", "7", "Backspace", "Tab", "10", "11", "Center", "Enter", "14", "15", "Shift", "Control", "Alt", "Pause", "Caps Lock", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "Space", "Page Up", "Page Down", "End", "Home", "Left", "Up", "Right", "Down", "41", "42", "43", "44", "Insert", "Delete", "47", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "58", "59", "60", "61", "62", "63", "64", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Windows", "Windows", "Menu", "94", "95", "Num 0", "Num 1", "Num 2", "Num 3", "Num 4", "Num 5", "Num 6", "Num 7", "Num 8", "Num 9", "Num *", "Num +", "108", "Num -", "Num .", "Num /", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "124", "125", "126", "127", "128", "129", "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", "143", "Num Lock", "Scroll Lock", "146", "147", "148", "149", "150", "151", "152", "153", "154", "155", "156", "157", "158", "159", "160", "161", "162", "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", "176", "177", "178", "179", "180", "181", "182", "183", "184", "185", ";", "+", ",", "-", ".", "/", "~", "193", "194", "195", "196", "197", "198", "199", "200", "201", "202", "203", "204", "205", "206", "207", "208", "209", "210", "211", "212", "213", "214", "215", "216", "217", "218", "[", "\\", "]", "'", "223", "224", "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", "253", "254", "255"]; public static const LEFT:uint = 37; public static const RIGHTBRACKET:uint = 221; public static const EQUAL:uint = 187; public static const COMMAND:uint = 15; public static const CONTROL:uint = 17; public static const NUMPAD_DECIMAL:uint = 110; public static const A:uint = 65; public static const B:uint = 66; public static const C:uint = 67; public static const D:uint = 68; public static const E:uint = 69; public static const F:uint = 70; public static const G:uint = 71; public static const H:uint = 72; public static const I:uint = 73; public static const J:uint = 74; public static const L:uint = 76; public static const M:uint = 77; public static const N:uint = 78; public static const O:uint = 79; public static const MINUS:uint = 189; public static const K:uint = 75; public static const S:uint = 83; public static const NUMPAD:uint = 21; public static const NUMPAD_ENTER:uint = 108; public static const P:uint = 80; public static const PAGE_DOWN:uint = 34; public static const ALTERNATE:uint = 18; public static const T:uint = 84; public static const BACKSPACE:uint = 8; public static const PAGE_UP:uint = 33; public static const X:uint = 88; public static const Y:uint = 89; public static const Q:uint = 81; public static const QUOTE:uint = 222; public static const SLASH:uint = 191; public static const U:uint = 85; public static const W:uint = 87; public static const SHIFT:uint = 16; public static const TAB:uint = 9; public static const R:uint = 82; public static const ESCAPE:uint = 27; public static const NUMPAD_ADD:uint = 107; public static const LEFTBRACKET:uint = 219; public static const DOWN:uint = 40; public static const F1:uint = 112; public static const F3:uint = 114; public static const F4:uint = 115; public static const F5:uint = 116; public static const F6:uint = 117; public static const F7:uint = 118; public static const F8:uint = 119; public static const F2:uint = 113; public static const COMMA:uint = 188; public static const ENTER:uint = 13; public static const INSERT:uint = 45; public static const DELETE:uint = 46; public static const NUMBER_1:uint = 49; public static const NUMBER_2:uint = 50; public static const NUMBER_3:uint = 51; public static const NUMBER_5:uint = 53; public static const NUMBER_6:uint = 54; public static const NUMBER_0:uint = 48; public static const END:uint = 35; public static const NUMBER_9:uint = 57; public static const NUMPAD_6:uint = 102; public static const NUMPAD_1:uint = 97; public static const NUMPAD_2:uint = 98; public static const NUMBER_7:uint = 55; public static const CAPS_LOCK:uint = 20; public static const F9:uint = 120; public static const NUMBER_4:uint = 52; public static const NUMBER_8:uint = 56; public static const BACKQUOTE:uint = 192; public static const BACKSLASH:uint = 220; public static const SEMICOLON:uint = 186; public static const NUMPAD_DIVIDE:uint = 111; public static const NUMPAD_3:uint = 99; public static const NUMPAD_4:uint = 100; public static const NUMPAD_5:uint = 101; public static const NUMPAD_7:uint = 103; public static const NUMPAD_8:uint = 104; public static const HOME:uint = 36; public static const NUMPAD_0:uint = 96; public static const PERIOD:uint = 190; public static const F10:uint = 121; public static const F11:uint = 122; public static const F12:uint = 123; public static const F13:uint = 124; public static const F14:uint = 125; public static const F15:uint = 126; public static const V:uint = 86; public static const SPACE:uint = 32; public static const NUMPAD_MULTIPLY:uint = 106; public static const NUMPAD_SUBTRACT:uint = 109; public static const NUMPAD_9:uint = 105; public static const RIGHT:uint = 39; public static const UP:uint = 38; public function KeyboardMap(){ super(); } } }//package com.urbansquall.prophet.input
Section 144
//KeyboardState (com.urbansquall.prophet.input.KeyboardState) package com.urbansquall.prophet.input { import flash.events.*; import flash.display.*; import flash.utils.*; public class KeyboardState { private var m_keyTemplate:KeyboardTemplate; private var m_stage:Stage; private var m_actionMap:Dictionary; private var m_keyRecords:Dictionary; private var m_previousActionMap:Dictionary; public function KeyboardState(a_stage:Stage, a_keyTemplate:KeyboardTemplate){ m_actionMap = new Dictionary(); m_previousActionMap = new Dictionary(); m_keyRecords = new Dictionary(); super(); m_keyTemplate = a_keyTemplate; m_stage = a_stage; m_stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, true); m_stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp, false, 0, true); } private function onKeyUp(a_keyboardEvent:KeyboardEvent):void{ var actionID:uint; var keyCode:uint = a_keyboardEvent.keyCode; if (m_keyTemplate.hasActionMatchingKeyCode(keyCode)){ actionID = m_keyTemplate.lookupActionIDMatchingKeyCode(keyCode); m_actionMap[actionID] = false; m_keyRecords[actionID] = false; }; } private function onKeyDown(a_keyboardEvent:KeyboardEvent):void{ var actionID:uint; var keyCode:uint = a_keyboardEvent.keyCode; if (m_keyTemplate.hasActionMatchingKeyCode(keyCode)){ actionID = m_keyTemplate.lookupActionIDMatchingKeyCode(keyCode); m_actionMap[actionID] = true; m_keyRecords[actionID] = true; }; } public function disableKeyListening():void{ m_stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); m_stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp); } public function forceUp(a_actionID:uint):void{ m_actionMap[a_actionID] = false; } public function wasDown(a_id:uint):Boolean{ if (m_previousActionMap[a_id] != null){ return (m_previousActionMap[a_id]); }; return (false); } public function wasJustPressed(a_id:uint):Boolean{ return (((isDown(a_id)) && (!(wasDown(a_id))))); } public function tick():void{ var action:String; m_previousActionMap = new Dictionary(); for (action in m_actionMap) { m_previousActionMap[action] = m_actionMap[action]; }; } public function isDown(a_id:uint):Boolean{ if (m_actionMap[a_id] != null){ return (m_actionMap[a_id]); }; return (false); } public function forceDown(a_actionID:uint):void{ m_actionMap[a_actionID] = true; } public function dispose():void{ disableKeyListening(); m_stage = null; m_actionMap = null; m_previousActionMap = null; m_keyTemplate = null; } } }//package com.urbansquall.prophet.input
Section 145
//KeyboardTemplate (com.urbansquall.prophet.input.KeyboardTemplate) package com.urbansquall.prophet.input { import flash.utils.*; public class KeyboardTemplate { private var m_array:Array; private var m_idMap:Dictionary; private var m_keyMap:Dictionary; public function KeyboardTemplate(){ super(); m_idMap = new Dictionary(); m_keyMap = new Dictionary(); m_array = new Array(); } public function registerAction(a_id:uint, a_description:String):void{ if (m_keyMap[a_id] != null){ throw (new Error((("InputTemplate.registerAction. There is already an action with that default key " + a_id) + "."))); }; if (m_idMap[a_id] != null){ throw (new Error((("InputTemplate.registerAction. There is already an action with the ID " + a_id) + "."))); }; var action:ActionHelper = new ActionHelper(a_id, a_description, a_id); m_keyMap[a_id] = action; m_idMap[a_id] = action; m_array.push(action); } public function resetDefaults():void{ var action:ActionHelper; var i:int; while (i < m_array.length) { action = m_array[i]; action.resetDefault(); i++; }; } public function lookupID(a_id:uint):uint{ var action:ActionHelper = m_idMap[a_id]; return (action.overrideKey); } public function getActionID(a_index:int):uint{ var action:ActionHelper = m_array[a_index]; return (action.id); } public function lookupActionIDMatchingKeyCode(a_keyCode:uint):uint{ var action:ActionHelper; var i:int; while (i < m_array.length) { action = m_array[i]; if (action.overrideKey == a_keyCode){ return (action.id); }; i++; }; throw (new Error(("KeyboardTemplate.lookupActionIDMatchingKeyCode. No matching key code for " + a_keyCode))); } public function getActionDescription(a_index:int):String{ var action:ActionHelper = m_array[a_index]; return (action.description); } public function lookupKeyCode(a_actionID:uint):uint{ var action:ActionHelper = m_keyMap[a_actionID]; return (action.overrideKey); } public function getActionDefault(a_index:int):uint{ var action:ActionHelper = m_array[a_index]; return (action.defaultKey); } public function get actionCount():int{ return (m_array.length); } public function getActionKey(a_index:int):uint{ var action:ActionHelper = m_array[a_index]; return (action.overrideKey); } public function overrideDefault(a_index:uint, a_overrideKey:uint):void{ var action:ActionHelper = m_array[a_index]; if (a_overrideKey == action.overrideKey){ return; }; if (m_keyMap[a_overrideKey] != null){ throw (new Error((("InputTemplate.overrideDefault. There is already an action with that key " + a_overrideKey) + "."))); }; delete m_keyMap[action.overrideKey]; action.overrideKey = a_overrideKey; m_keyMap[action.overrideKey] = action; } public function hasActionMatchingKeyCode(a_keyCode:uint):Boolean{ var action:ActionHelper; var i:int; while (i < m_array.length) { action = m_array[i]; if (action.overrideKey == a_keyCode){ return (true); }; i++; }; return (false); } } }//package com.urbansquall.prophet.input class ActionHelper { public var overrideKey:uint; public var id:uint; public var description:String; public var defaultKey:uint; private function ActionHelper(a_id:uint, a_description:String, a_defaultKey:uint){ super(); id = a_id; description = a_description; defaultKey = a_defaultKey; overrideKey = defaultKey; } public function resetDefault():void{ overrideKey = defaultKey; } }
Section 146
//BoundaryListener (com.urbansquall.prophet.physics.BoundaryListener) package com.urbansquall.prophet.physics { import Box2D.Dynamics.*; public class BoundaryListener extends b2BoundaryListener { private var m_violators:Array; private var m_hadViolation:Boolean;// = false private var m_dynamics:Dynamics; public function BoundaryListener(a_dynamics:Dynamics){ m_violators = []; super(); m_dynamics = a_dynamics; } override public function Violation(body:b2Body):void{ m_hadViolation = true; m_violators.push(body); } function processResults():void{ if (!m_hadViolation){ return; }; var i:int; while (i < m_violators.length) { m_dynamics.handleBodyHitWorldBoundary(m_violators[i]); i++; }; m_violators.slice(0); m_hadViolation = false; } } }//package com.urbansquall.prophet.physics
Section 147
//CircleDef (com.urbansquall.prophet.physics.CircleDef) package com.urbansquall.prophet.physics { import flash.geom.*; import Box2D.Collision.Shapes.*; public class CircleDef extends ShapeDef { public var radius:Number;// = 1 public var localPosition:Point; public function CircleDef(){ super(); localPosition = new Point(0, 0); } override public function createBox2DShape(a_scale:Number):b2ShapeDef{ var box2DCircle:b2CircleDef = new b2CircleDef(); box2DCircle.radius = (radius * a_scale); box2DCircle.localPosition.Set((localPosition.x * a_scale), (localPosition.y * a_scale)); box2DCircle.density = (density * Dynamics.INVERSE_SCALE); box2DCircle.restitution = restitution; box2DCircle.friction = friction; box2DCircle.isSensor = isSensor; if (groupFilter != 0){ box2DCircle.filter.groupIndex = groupFilter; }; box2DCircle.filter.maskBits = maskBits; box2DCircle.filter.categoryBits = categoryBits; return (box2DCircle); } override public function clone():ShapeDef{ var circDef:CircleDef; circDef = new CircleDef(); circDef.friction = friction; circDef.restitution = restitution; circDef.density = density; circDef.isSensor = isSensor; circDef.groupFilter = groupFilter; circDef.radius = radius; circDef.localPosition.x = localPosition.x; circDef.localPosition.y = localPosition.y; circDef.categoryBits = categoryBits; circDef.maskBits = maskBits; return (circDef); } } }//package com.urbansquall.prophet.physics
Section 148
//ContactListener (com.urbansquall.prophet.physics.ContactListener) package com.urbansquall.prophet.physics { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; public class ContactListener extends b2ContactListener { private var m_persisted:Array; private var m_added:Array; private var m_removed:Array; public function ContactListener(){ super(); m_added = new Array(); m_removed = new Array(); m_persisted = new Array(); } override public function Remove(a_point:b2ContactPoint):void{ super.Remove(a_point); m_removed.push(new CustomContactPoint(a_point)); } override public function Persist(a_point:b2ContactPoint):void{ super.Persist(a_point); m_persisted.push(new CustomContactPoint(a_point)); } public function processResults():void{ var p:CustomContactPoint; var shape:b2Shape; var entity1:Entity; var entity2:Entity; var shape1:b2Shape; var shape2:b2Shape; var nuke_obj:Array = new Array(); while ((p = m_added.pop())) { shape1 = p.m_shape1; shape2 = p.m_shape2; if ((((shape1 == null)) || ((shape2 == null)))){ } else { if ((((shape1.GetBody() == null)) || ((shape2.GetBody() == null)))){ } else { entity1 = shape1.GetBody().GetUserData(); entity2 = shape2.GetBody().GetUserData(); if (entity1.hasEventListener(EngineEvent.BEGIN_TOUCH)){ entity1.dispatchEvent(new BeginTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape1, shape2, entity1, entity2)); }; if (entity2.hasEventListener(EngineEvent.BEGIN_TOUCH)){ entity2.dispatchEvent(new BeginTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape2, shape1, entity2, entity1)); }; }; }; }; while ((p = m_persisted.pop())) { shape1 = p.m_shape1; shape2 = p.m_shape2; if ((((shape1 == null)) || ((shape2 == null)))){ } else { if ((((shape1.GetBody() == null)) || ((shape2.GetBody() == null)))){ } else { entity1 = shape1.GetBody().GetUserData(); entity2 = shape2.GetBody().GetUserData(); if (entity1.hasEventListener(EngineEvent.PERSIST_TOUCH)){ entity1.dispatchEvent(new PersistTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape1, shape2, entity1, entity2)); }; if (entity2.hasEventListener(EngineEvent.PERSIST_TOUCH)){ entity2.dispatchEvent(new PersistTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape2, shape1, entity2, entity1)); }; }; }; }; while ((p = m_removed.pop())) { shape1 = p.m_shape1; shape2 = p.m_shape2; if ((((shape1 == null)) || ((shape2 == null)))){ } else { if ((((shape1.GetBody() == null)) || ((shape2.GetBody() == null)))){ } else { entity1 = shape1.GetBody().GetUserData(); entity2 = shape2.GetBody().GetUserData(); if (entity1.hasEventListener(EngineEvent.END_TOUCH)){ entity1.dispatchEvent(new EndTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape1, shape2, entity1, entity2)); }; if (entity2.hasEventListener(EngineEvent.END_TOUCH)){ entity2.dispatchEvent(new EndTouchEvent(convertToEngineCoordinates(p.m_position), convertToEngineCoordinates(p.m_normal), convertToEngineCoordinates(p.m_velocity), shape2, shape1, entity2, entity1)); }; }; }; }; } override public function Add(a_point:b2ContactPoint):void{ super.Add(a_point); m_added.push(new CustomContactPoint(a_point)); } public function convertToEngineCoordinates(a_source:b2Vec2):b2Vec2{ var result:b2Vec2 = new b2Vec2((a_source.x * Dynamics.INVERSE_SCALE), (a_source.y * Dynamics.INVERSE_SCALE)); return (result); } } }//package com.urbansquall.prophet.physics
Section 149
//CustomContactPoint (com.urbansquall.prophet.physics.CustomContactPoint) package com.urbansquall.prophet.physics { import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; import Box2D.Collision.*; public class CustomContactPoint { public var m_shape1:b2Shape; public var m_shape2:b2Shape; public var m_normal:b2Vec2; public var m_position:b2Vec2; public var m_velocity:b2Vec2; public function CustomContactPoint(a_point:b2ContactPoint){ super(); m_shape1 = a_point.shape1; m_shape2 = a_point.shape2; m_normal = a_point.normal; m_velocity = a_point.velocity; m_position = a_point.position; } } }//package com.urbansquall.prophet.physics
Section 150
//Dynamics (com.urbansquall.prophet.physics.Dynamics) package com.urbansquall.prophet.physics { import flash.events.*; import flash.display.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.Joints.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; import Box2D.Collision.*; public class Dynamics extends EventDispatcher { private var m_world:b2World; private var m_contactListener:ContactListener; private var m_debugDraw:Sprite; private var m_boundaryListener:BoundaryListener; public static const SCALE:Number = 0; public static const INVERSE_SCALE:Number = 30; public function Dynamics(a_debugDraw:Sprite=null){ super(); m_debugDraw = a_debugDraw; } public function destroyBody(a_body:b2Body):void{ m_world.DestroyBody(a_body); } public function getBodiesInBox(a_x:Number, a_y:Number, a_width:Number, a_height:Number, includeStatic:Boolean=false, a_allowSensors:Boolean=false, a_allowTileDefinitions:Boolean=false):Array{ var shape:b2Shape; var result:Array = []; var realX:Number = scaleForBox2D(a_x); var realY:Number = scaleForBox2D(a_y); var realWidth:Number = scaleForBox2D(a_width); var realHeight:Number = scaleForBox2D(a_height); var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(realX, realY); aabb.upperBound.Set((realX + realWidth), (realY + realHeight)); var k_maxCount = 200; var shapes:Array = new Array(); var count:int = m_world.Query(aabb, shapes, k_maxCount); var body:b2Body; var i:int; while (i < count) { shape = shapes[i]; if (((!(a_allowTileDefinitions)) && ((shape.GetUserData() is TileDefinition)))){ } else { if (((shape.IsSensor()) && (!(a_allowSensors)))){ } else { if (((shape.GetBody().IsStatic()) && (!(includeStatic)))){ } else { result.push(shape.GetBody()); }; }; }; i++; }; return (result); } public function refilter(a_shape:b2Shape):void{ m_world.Refilter(a_shape); } public function step(a_stepSize:Number):void{ m_world.Step((a_stepSize / 1000), 10, 8); m_contactListener.processResults(); m_boundaryListener.processResults(); } public function createBody(a_bodyDef:b2BodyDef, a_fixed:Boolean, a_shapes:Array, a_x:Number, a_y:Number, a_vx:Number, a_vy:Number, a_rotation:Number, a_scale:Number):b2Body{ var shapeDef:ShapeDef; var box2DShape:b2ShapeDef; var bodyDef:b2BodyDef = a_bodyDef; bodyDef.position.x = scaleForBox2D(a_x); bodyDef.position.y = scaleForBox2D(a_y); var body:b2Body = m_world.CreateBody(bodyDef); body.SetXForm(body.GetPosition(), (a_rotation * 0.0174532925)); body.SetLinearVelocity(new b2Vec2(scaleForBox2D(a_vx), scaleForBox2D(a_vy))); var s:int; while (s < a_shapes.length) { shapeDef = a_shapes[s]; box2DShape = shapeDef.createBox2DShape((SCALE * a_scale)); if (shapeDef.userData != null){ box2DShape.userData = shapeDef.userData; }; body.CreateShape(box2DShape); s++; }; if (!a_fixed){ body.SetMassFromShapes(); }; return (body); } public function createJoint(a_jointDef:b2JointDef):b2Joint{ return (m_world.CreateJoint(a_jointDef)); } public function getBodyAtPoint(a_pointX:Number, a_pointY:Number, includeStatic:Boolean=false, a_ignoredBodies:Array=null):b2Body{ var tShape:b2Shape; var inside:Boolean; var real_x_mouse:Number = scaleForBox2D(a_pointX); var real_y_mouse:Number = scaleForBox2D(a_pointY); var mousePVec:b2Vec2 = new b2Vec2(real_x_mouse, real_y_mouse); var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set((real_x_mouse - 0.001), (real_y_mouse - 0.001)); aabb.upperBound.Set((real_x_mouse + 0.001), (real_y_mouse + 0.001)); var k_maxCount = 10; var shapes:Array = new Array(); var count:int = m_world.Query(aabb, shapes, k_maxCount); var body:b2Body; var i:int; while (i < count) { if ((((shapes[i].GetBody().IsStatic() == false)) || (includeStatic))){ if (a_ignoredBodies != null){ //unresolved if } else { tShape = (shapes[i] as b2Shape); inside = tShape.TestPoint(tShape.GetBody().GetXForm(), mousePVec); if (inside){ body = tShape.GetBody(); break; }; }; }; i++; }; return (body); } function handleBodyHitWorldBoundary(a_body:b2Body):void{ dispatchEvent(new HitWorldBoundaryEvent(a_body)); } public function destroyJoint(a_joint:b2Joint):void{ m_world.DestroyJoint(a_joint); } public function setupDebugDraw():void{ var dbgDraw:b2DebugDraw; if (m_debugDraw != null){ dbgDraw = new b2DebugDraw(); dbgDraw.SetSprite(m_debugDraw); dbgDraw.SetDrawScale(INVERSE_SCALE); dbgDraw.SetFillAlpha(0.8); dbgDraw.SetLineThickness(1); dbgDraw.SetFlags(((b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit) | b2DebugDraw.e_controllerBit)); m_world.SetDebugDraw(dbgDraw); }; } public function create(a_levelDefinition:LevelDefinition):void{ var worldAABB:b2AABB = new b2AABB(); worldAABB.lowerBound.Set(scaleForBox2D(a_levelDefinition.worldBoundX), scaleForBox2D(a_levelDefinition.worldBoundY)); worldAABB.upperBound.Set(scaleForBox2D((a_levelDefinition.worldBoundX + a_levelDefinition.worldBoundWidth)), scaleForBox2D((a_levelDefinition.worldBoundY + a_levelDefinition.worldBoundHeight))); var gravity:b2Vec2 = new b2Vec2(a_levelDefinition.gravityX, a_levelDefinition.gravityY); m_world = new b2World(worldAABB, gravity, a_levelDefinition.allowSleep); m_contactListener = new ContactListener(); m_world.SetContactListener(m_contactListener); m_boundaryListener = new BoundaryListener(this); m_world.SetBoundaryListener(m_boundaryListener); setupDebugDraw(); } private function scaleForBox2D(a_original:Number):Number{ return ((a_original * SCALE)); } public function dispose():void{ if (((!((m_debugDraw == null))) && (!((m_debugDraw.parent == null))))){ m_debugDraw.parent.removeChild(m_debugDraw); }; } } }//package com.urbansquall.prophet.physics
Section 151
//HitWorldBoundaryEvent (com.urbansquall.prophet.physics.HitWorldBoundaryEvent) package com.urbansquall.prophet.physics { import flash.events.*; import Box2D.Dynamics.*; public class HitWorldBoundaryEvent extends Event { public var body:b2Body; public static const HIT_WORLD_BOUNDARY:String = "hit_world_boundary"; public function HitWorldBoundaryEvent(a_body:b2Body){ super(HIT_WORLD_BOUNDARY); body = a_body; } } }//package com.urbansquall.prophet.physics
Section 152
//PolygonDef (com.urbansquall.prophet.physics.PolygonDef) package com.urbansquall.prophet.physics { import flash.geom.*; import Box2D.Collision.Shapes.*; public class PolygonDef extends ShapeDef { private var m_vertices:Array; public function PolygonDef(){ m_vertices = []; super(); } override public function createBox2DShape(a_scale:Number):b2ShapeDef{ var vertex:Point; if (m_vertices.length == 0){ throw (new Error("Can't create polygon with 0 vertices.")); }; var box2DPoly:b2PolygonDef = new b2PolygonDef(); box2DPoly.density = (density * Dynamics.INVERSE_SCALE); box2DPoly.restitution = restitution; box2DPoly.friction = friction; box2DPoly.isSensor = isSensor; if (groupFilter != 0){ box2DPoly.filter.groupIndex = groupFilter; }; box2DPoly.filter.maskBits = maskBits; box2DPoly.filter.categoryBits = categoryBits; box2DPoly.vertexCount = m_vertices.length; var i:int; while (i < m_vertices.length) { vertex = m_vertices[i]; box2DPoly.vertices[i].Set((a_scale * vertex.x), (a_scale * vertex.y)); i++; }; return (box2DPoly); } public function getVerticesCopy():Array{ return (m_vertices.slice()); } public function addVertex(a_x:Number, a_y:Number):void{ m_vertices.push(new Point(a_x, a_y)); } public function makeCenteredBox(a_halfWidth:Number, a_halfHeight:Number, a_offsetX:Number=0, a_offsetY:Number=0):void{ if (m_vertices.length != 0){ throw (new Error("DEATH")); }; addVertex((-(a_halfWidth) + a_offsetX), (-(a_halfHeight) + a_offsetY)); addVertex((a_halfWidth + a_offsetX), (-(a_halfHeight) + a_offsetY)); addVertex((a_halfWidth + a_offsetX), (a_halfHeight + a_offsetY)); addVertex((-(a_halfWidth) + a_offsetX), (a_halfHeight + a_offsetY)); } public function setAsOrientedBox(hx:Number, hy:Number, center:Point=null, angle:Number=0):void{ throw (new Error("Not supported. Can be added though. See b2PolygonDef.setAsOrientedBox")); } public function makeBox(a_x:Number, a_y:Number, a_width:Number, a_height:Number):void{ if (m_vertices.length != 0){ throw (new Error("DEATH")); }; addVertex(a_x, a_y); addVertex((a_x + a_width), a_y); addVertex((a_x + a_width), (a_y + a_height)); addVertex(a_x, (a_y + a_height)); } override public function clone():ShapeDef{ var polyDef:PolygonDef; polyDef = new PolygonDef(); polyDef.friction = friction; polyDef.restitution = restitution; polyDef.density = density; polyDef.isSensor = isSensor; polyDef.groupFilter = groupFilter; polyDef.m_vertices = m_vertices.slice(); polyDef.categoryBits = categoryBits; polyDef.maskBits = maskBits; return (polyDef); } } }//package com.urbansquall.prophet.physics
Section 153
//ShapeDef (com.urbansquall.prophet.physics.ShapeDef) package com.urbansquall.prophet.physics { import Box2D.Collision.Shapes.*; public class ShapeDef { public var isSensor:Boolean;// = false public var restitution:Number;// = 0 public var categoryBits:int;// = 1 public var density:Number;// = 0 public var maskBits:int;// = 1 public var userData;// = null public var groupFilter:int;// = 0 public var friction:Number;// = 0.2 public function ShapeDef(){ super(); } public function createBox2DShape(a_scale:Number):b2ShapeDef{ throw (new Error("Your shapedef subclass must override this!")); } public function clone():ShapeDef{ throw (new Error("Define ShapeDef.clone in your subclass.")); } } }//package com.urbansquall.prophet.physics
Section 154
//EditorButtonFactory (com.urbansquall.prophet.tilemaps.editor.EditorButtonFactory) package com.urbansquall.prophet.tilemaps.editor { import flash.display.*; import flash.geom.*; import flash.text.*; import com.urbansquall.ui.*; import com.urbansquall.display.*; public class EditorButtonFactory extends VistaButtonFactory { private var m_tile9Data:Tile9Data; private var m_buttonOverlay:BitmapData; private static const DESCRIPTION_COLOR:uint = 6773846; private static const HEADER_COLOR:uint = 0; private static var s_instance:EditorButtonFactory = null; public function EditorButtonFactory(){ var buttonBackground:Sprite = new Sprite(); buttonBackground.graphics.beginFill(0xC0C0C0); buttonBackground.graphics.lineStyle(1, 0); buttonBackground.graphics.drawRoundRect(0, 0, 20, 20, 5, 5); var buttonBitmapData:BitmapData = new BitmapData(20, 20, true, 0); buttonBitmapData.draw(buttonBackground); m_tile9Data = new Tile9Data(new Bitmap(buttonBitmapData), new Rectangle(6, 6, 8, 8)); var buttonOverlay:Sprite = new Sprite(); buttonOverlay.graphics.beginGradientFill(GradientType.LINEAR, [0xFFFFFF, 0], [0, 0.5], [0, 0xFF]); buttonOverlay.graphics.drawRoundRect(0, 0, 20, 20, 5, 5); m_buttonOverlay = new BitmapData(20, 20, true, 0); m_buttonOverlay.draw(buttonOverlay); super(HEADER_COLOR, DESCRIPTION_COLOR, 52, 30, m_tile9Data, m_buttonOverlay); } override public function createHeaderTextField():TextField{ var textfield:TextField = new TextField(); textfield.selectable = false; textfield.mouseEnabled = false; return (textfield); } override public function createDescriptionTextField():TextField{ var textfield:TextField = new TextField(); textfield.selectable = false; textfield.mouseEnabled = false; return (textfield); } public static function get instance():EditorButtonFactory{ if (s_instance == null){ s_instance = new (EditorButtonFactory); }; return (s_instance); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 155
//EditorToolTip (com.urbansquall.prophet.tilemaps.editor.EditorToolTip) package com.urbansquall.prophet.tilemaps.editor { import flash.display.*; import flash.text.*; import com.urbansquall.ui.*; public class EditorToolTip { public function EditorToolTip(){ super(); } public static function attachToolTip(a_target:DisplayObject, a_description:String):void{ var container:Sprite = new Sprite(); var descriptionTF:TextField = new TextField(); descriptionTF.mouseEnabled = false; descriptionTF.autoSize = "left"; descriptionTF.text = ((" " + a_description) + " "); descriptionTF.background = true; descriptionTF.backgroundColor = 0xFFFFFF; descriptionTF.border = true; descriptionTF.borderColor = 0; container.addChild(descriptionTF); ToolTip.attachToolTip(a_target, container); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 156
//EntityLibraryPanel (com.urbansquall.prophet.tilemaps.editor.EntityLibraryPanel) package com.urbansquall.prophet.tilemaps.editor { import flash.events.*; import flash.display.*; import flash.text.*; import com.urbansquall.prophet.definitions.*; public class EntityLibraryPanel extends Sprite { private var m_entityGraphics:Array; private var m_activeEntityName:String;// = "" private var m_gameDefinition:GameDefinition; private static const ENTRY_WIDTH:Number = 60; private static const ENTRY_HEIGHT:Number = 60; public function EntityLibraryPanel(a_gameDefinition:GameDefinition){ m_entityGraphics = []; super(); m_gameDefinition = a_gameDefinition; this.addEventListener(Event.ADDED_TO_STAGE, addedToStage); } private function addedToStage(a_event:Event):void{ var entityGraphic:Sprite; var entityDefinition:EntityTypeDefinition; var entityName:String; var graphic:GraphicDefinition; var entityDefinitionBackgroundColor:uint; var row:int; var col:int; var display:DisplayObject; var scale:Number; this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage); var entriesPerRow:int = Math.floor((this.stage.stageWidth / ENTRY_WIDTH)); var entriesCount:int = m_gameDefinition.entityDefinitionCount; var entityGraphicContainer:Sprite = new Sprite(); addChild(entityGraphicContainer); entityGraphic = new Sprite(); entityGraphic.name = "none"; var nameLabel:TextField = new TextField(); nameLabel.text = entityGraphic.name; nameLabel.selectable = false; nameLabel.width = 60; nameLabel.height = 20; entityGraphic.addChild(nameLabel); entityGraphic.graphics.beginFill(0xFFFFFF); entityGraphic.graphics.drawRect(0, 0, entityGraphic.width, entityGraphic.height); entityGraphicContainer.addChild(entityGraphic); entityGraphic.addEventListener(MouseEvent.CLICK, clickEntityDefinition); m_entityGraphics.push(entityGraphic); var firstTileDefName:String = ""; var names:Array = []; var i:int; while (i < m_gameDefinition.entityDefinitionCount) { entityDefinition = m_gameDefinition.getIndexedEntityDefinition(i); names.push(entityDefinition.type); i++; }; names.sort(); i = 0; while (i < names.length) { entityName = names[i]; entityDefinition = m_gameDefinition.lookupEntityType(entityName); if (firstTileDefName == ""){ firstTileDefName = entityDefinition.type; }; entityGraphic = new Sprite(); nameLabel = new TextField(); nameLabel.text = entityDefinition.type; nameLabel.selectable = false; nameLabel.width = 60; nameLabel.height = 20; entityGraphic.addChild(nameLabel); for each (graphic in entityDefinition.graphics) { if ((graphic is StaticGraphicDefinition)){ display = (graphic as StaticGraphicDefinition).createGraphic(1).display; } else { if ((graphic is GingerGraphicDefinition)){ display = (graphic as GingerGraphicDefinition).createGraphic(1).display; } else { break; }; }; scale = 1; if ((((display.width > ENTRY_WIDTH)) || ((display.height > ENTRY_HEIGHT)))){ if ((display.height - ENTRY_HEIGHT) > (display.width - ENTRY_WIDTH)){ scale = (ENTRY_HEIGHT / display.height); } else { scale = (ENTRY_WIDTH / display.width); }; }; display.scaleX = scale; display.scaleY = scale; display.x = (ENTRY_WIDTH / 2); display.y = (ENTRY_HEIGHT / 2); entityGraphic.addChild(display); }; entityDefinitionBackgroundColor = 0xC0C0C0; if ((i % 2) == 0){ entityDefinitionBackgroundColor = 0xB9B9B9; }; entityGraphic.graphics.beginFill(entityDefinitionBackgroundColor); entityGraphic.graphics.drawRect(0, 0, ENTRY_WIDTH, ENTRY_HEIGHT); entityGraphic.name = entityDefinition.type; entityGraphic.addEventListener(MouseEvent.CLICK, clickEntityDefinition, false, 100); row = Math.floor((i / entriesPerRow)); col = Math.floor((i % entriesPerRow)); entityGraphic.x = (col * ENTRY_WIDTH); entityGraphic.y = (row * ENTRY_HEIGHT); entityGraphicContainer.addChild(entityGraphic); m_entityGraphics.push(entityGraphic); i++; }; var background:Sprite = new Sprite(); background.graphics.lineStyle(1); background.graphics.beginFill(0xFFFFFF); background.graphics.drawRect(0, 0, this.width, this.height); addChildAt(background, 0); selectEntityDefinition(firstTileDefName); } private function selectEntityDefinition(a_name:String):void{ var entityGraphic:Sprite; if (a_name == "none"){ a_name = ""; }; m_activeEntityName = a_name; var i:int; while (i < m_entityGraphics.length) { entityGraphic = m_entityGraphics[i]; if (entityGraphic.name == a_name){ entityGraphic.alpha = 1; } else { entityGraphic.alpha = 0.5; }; i++; }; } public function get activeEntityName():String{ return (m_activeEntityName); } public function select(a_name:String):void{ selectEntityDefinition(a_name); } private function clickEntityDefinition(a_event:Event):void{ var tileDefName:String = (a_event.currentTarget as DisplayObject).name; selectEntityDefinition(tileDefName); dispatchEvent(new Event(Event.SELECT)); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 157
//LevelEditor (com.urbansquall.prophet.tilemaps.editor.LevelEditor) package com.urbansquall.prophet.tilemaps.editor { import flash.events.*; import flash.display.*; import flash.geom.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import flash.text.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import com.urbansquall.prophet.input.*; import flash.utils.*; import flash.system.*; public class LevelEditor extends Sprite { private var m_tileMode:Boolean;// = false private var m_levelXML:XML; private var m_entityLibrary:GameDefinition; private var m_superTileColCount:int;// = 0 private var m_mouseDown:Boolean;// = false private var m_columnsInSuperTile:int; private var m_showEntityLibraryButton:VistaButton; private var m_entityLibraryPanel:EntityLibraryPanel; private var m_tileSetButtons:Array; private var m_supportedDepths:Array; private var m_lastEntity:Entity; private var m_container:Sprite; private var m_propertiesOfLastPickedObject:KeyValueMap;// = null private var m_tileLibraries:Array; private var m_activeTilePanel:TileLibraryPanel; private var m_background:Sprite; private var m_rowsInSuperTile:int; private var m_engine:Engine; private var m_previewObject:Sprite; private var m_tileLibrary:TileLibrary; private var m_tileDepthPanel:TileDepthPanel; private var m_pixelSnappingPanel:PixelSnappingPanel; private var m_tileMapDefinitions:Array; private var m_selectedIndicator:TextField; private var m_superTileRowCount:int;// = 0 public function LevelEditor(a_entityLibrary:GameDefinition, a_tileLibrary:TileLibrary, a_supportedDepths:Array){ var entityDefinition:EntityTypeDefinition; var s:int; var shapeDef:ShapeDef; m_tileSetButtons = []; m_tileLibraries = []; super(); m_supportedDepths = a_supportedDepths; m_entityLibrary = a_entityLibrary.clone(); var i:int; while (i < m_entityLibrary.entityDefinitionCount) { entityDefinition = m_entityLibrary.getIndexedEntityDefinition(i); entityDefinition.behaviors.splice(0); s = 0; while (s < entityDefinition.shapes.length) { shapeDef = entityDefinition.shapes[s]; shapeDef.isSensor = true; s++; }; entityDefinition.fixed = true; i++; }; m_tileLibrary = a_tileLibrary; m_tileMapDefinitions = []; this.addEventListener(Event.ADDED_TO_STAGE, addedToStage); } private function onUpdate(a_event:Event):void{ var bitmap:Bitmap; var g:int; var graphic:Graphic; var tileCoords:Point; var tileCol:int; var tileRow:int; var tileDefinition:TileDefinition; var entityDefinition:EntityTypeDefinition; var hadEditorGraphics:Boolean; var graphicDefinition:GraphicDefinition; var display:DisplayObject; var objectX:int; var objectY:int; var snapSize:int; var snapTileX:int; var snapTileY:int; var levelXML:XML; var tileCount:int; var sc:int; var sr:int; var tileMapDef:TileMapDefinition; var c:int; var r:int; var types:Array; var tileSetButton:VistaButton; var mouseX:int = m_engine.renderer.mouseX; var mouseY:int = m_engine.renderer.mouseY; if ((((mouseX < 0)) || ((mouseY < 0)))){ m_selectedIndicator.text = "Invalid mouse location"; }; var mousePickedEntity:Entity = m_engine.pickEntity(mouseX, mouseY, true); if (mousePickedEntity != null){ if (mousePickedEntity.properties.getBoolean("EDITOR_SELECTABLE", true)){ if (((!((m_lastEntity == null))) && (!((m_lastEntity == mousePickedEntity))))){ g = 0; while (g < m_lastEntity.graphics.length) { graphic = m_lastEntity.graphics[g]; graphic.display.alpha = 1; g++; }; }; g = 0; while (g < mousePickedEntity.graphics.length) { graphic = mousePickedEntity.graphics[g]; graphic.display.alpha = 0.5; g++; }; m_lastEntity = mousePickedEntity; }; } else { if (((!((m_lastEntity == null))) && (!((m_lastEntity == mousePickedEntity))))){ g = 0; while (g < m_lastEntity.graphics.length) { graphic = m_lastEntity.graphics[g]; graphic.display.alpha = 1; g++; }; }; }; m_pixelSnappingPanel.visible = false; if (((((m_tileMode) && (!((m_activeTilePanel == null))))) && (!((m_activeTilePanel.activeTileName == ""))))){ tileCoords = getTileCoordinatesUnderMouse(); tileCol = tileCoords.x; tileRow = tileCoords.y; m_selectedIndicator.text = (((((("TILE: " + m_activeTilePanel.activeTileName) + " [") + tileCol) + ",") + tileRow) + "]"); if (m_mouseDown){ processTileClick(); }; if ((((m_previewObject == null)) || (((!((m_previewObject == null))) && (!((m_previewObject.name == m_activeTilePanel.activeTileName))))))){ if (m_previewObject != null){ m_previewObject.parent.removeChild(m_previewObject); }; m_previewObject = new Sprite(); m_container.addChild(m_previewObject); m_previewObject.name = m_activeTilePanel.activeTileName; if (m_activeTilePanel.activeTileName == "delete"){ m_previewObject.graphics.beginFill(0xFF0000, 0.75); m_previewObject.graphics.drawRect(0, 0, m_tileLibrary.tileWidth, m_tileLibrary.tileHeight); } else { tileDefinition = m_tileLibrary.lookupTileDefinition(m_activeTilePanel.activeTileName); if (tileDefinition.simpleBitmapData != null){ bitmap = new Bitmap(tileDefinition.simpleBitmapData); } else { bitmap = new Bitmap(); }; m_previewObject.addChild(bitmap); }; }; } else { if (m_entityLibraryPanel.activeEntityName != ""){ m_selectedIndicator.text = (((((("ENTITY: " + m_entityLibraryPanel.activeEntityName) + "[") + mouseX) + ",") + mouseY) + "]"); m_pixelSnappingPanel.visible = true; if ((((m_previewObject == null)) || (((!((m_previewObject == null))) && (!((m_previewObject.name == m_entityLibraryPanel.activeEntityName))))))){ if (m_previewObject != null){ trace(((("preview object changed, so reset - it used to be " + m_previewObject.name) + " and now it is ") + m_entityLibraryPanel.activeEntityName)); m_propertiesOfLastPickedObject = null; }; if (m_previewObject != null){ m_previewObject.parent.removeChild(m_previewObject); }; entityDefinition = m_entityLibrary.lookupEntityType(m_entityLibraryPanel.activeEntityName); m_previewObject = new Sprite(); m_container.addChild(m_previewObject); m_previewObject.name = m_entityLibraryPanel.activeEntityName; hadEditorGraphics = false; for each (graphicDefinition in entityDefinition.editorGraphics) { hadEditorGraphics = true; if ((graphicDefinition is StaticGraphicDefinition)){ display = (graphicDefinition as StaticGraphicDefinition).createGraphic(1).display; } else { if ((graphicDefinition is GingerGraphicDefinition)){ display = (graphicDefinition as GingerGraphicDefinition).createGraphic(1).display; } else { if ((graphicDefinition is PolygonGraphicDefinition)){ display = (graphicDefinition as PolygonGraphicDefinition).createGraphic(1).display; } else { break; }; }; }; m_previewObject.addChild(display); }; if (!hadEditorGraphics){ for each (graphicDefinition in entityDefinition.graphics) { if ((graphicDefinition is StaticGraphicDefinition)){ display = (graphicDefinition as StaticGraphicDefinition).createGraphic(1).display; } else { if ((graphicDefinition is GingerGraphicDefinition)){ display = (graphicDefinition as GingerGraphicDefinition).createGraphic(1).display; } else { if ((graphicDefinition is PolygonGraphicDefinition)){ display = (graphicDefinition as PolygonGraphicDefinition).createGraphic(1).display; } else { break; }; }; }; m_previewObject.addChild(display); }; }; }; } else { m_selectedIndicator.text = "NOTHING."; }; }; if (m_previewObject != null){ m_previewObject.mouseChildren = false; m_previewObject.mouseEnabled = false; objectX = mouseX; objectY = mouseY; if (m_pixelSnappingPanel.visible){ snapSize = m_pixelSnappingPanel.snapSize; } else { snapSize = Math.min(m_tileLibrary.tileWidth, m_tileLibrary.tileHeight); }; if (m_tileMode){ snapTileX = Math.floor((objectX / snapSize)); snapTileY = Math.floor((objectY / snapSize)); } else { snapTileX = Math.round((objectX / snapSize)); snapTileY = Math.round((objectY / snapSize)); }; objectX = (snapTileX * snapSize); objectY = (snapTileY * snapSize); m_previewObject.x = objectX; m_previewObject.y = objectY; }; var keyboardState:KeyboardState = m_engine.keyboardState; if (keyboardState.wasJustPressed(KeyboardMap.S)){ levelXML = exportXML(); trace(""); trace("EXPORTING"); trace(""); System.setClipboard(levelXML); }; var viewX:Number = m_engine.renderer.view.viewX; var viewY:Number = m_engine.renderer.view.viewY; var horizontalMoveSpeed:Number = (m_tileLibrary.tileWidth / 4); var verticalMoveSpeed:Number = (m_tileLibrary.tileHeight / 4); if (keyboardState.isDown(KeyboardMap.LEFT)){ viewX = (viewX - horizontalMoveSpeed); }; if (keyboardState.isDown(KeyboardMap.RIGHT)){ viewX = (viewX + horizontalMoveSpeed); }; if (keyboardState.isDown(KeyboardMap.UP)){ viewY = (viewY - verticalMoveSpeed); }; if (keyboardState.isDown(KeyboardMap.DOWN)){ viewY = (viewY + verticalMoveSpeed); }; if (keyboardState.wasJustPressed(KeyboardMap.T)){ tileCount = 0; sc = 0; while (sc < m_superTileColCount) { sr = 0; while (sr < m_superTileRowCount) { trace("sc", sc, sr); tileMapDef = m_tileMapDefinitions[sc][sr]; if (tileMapDef != null){ c = 0; while (c < m_columnsInSuperTile) { r = 0; while (r < m_rowsInSuperTile) { types = tileMapDef.getTileTypes(c, r); if (types.length > 0){ tileCount++; }; r++; }; c++; }; }; sr++; }; sc++; }; trace(("tile count " + tileCount)); }; if (keyboardState.wasJustPressed(KeyboardMap.E)){ clickShowEntityLibrary(null); }; var numbers:Array = [KeyboardMap.NUMBER_1, KeyboardMap.NUMBER_2, KeyboardMap.NUMBER_3, KeyboardMap.NUMBER_4, KeyboardMap.NUMBER_5, KeyboardMap.NUMBER_6, KeyboardMap.NUMBER_7, KeyboardMap.NUMBER_8, KeyboardMap.NUMBER_9]; var n:int; while (n < numbers.length) { if (keyboardState.wasJustPressed(numbers[n])){ if (n >= m_tileSetButtons.length){ } else { tileSetButton = m_tileSetButtons[n]; selectTileLibrary(tileSetButton.name); }; }; n++; }; m_engine.renderer.view.setTarget(viewX, viewY); } private function getTileMapDefinition(a_globalCol:int, a_globalRow:int):TileMapDefinition{ var superTileCol:int = getSuperTileCol(a_globalCol); var superTileRow:int = getSuperTileRow(a_globalRow); m_superTileColCount = Math.max(m_superTileColCount, (superTileCol + 1)); m_superTileRowCount = Math.max(m_superTileRowCount, (superTileRow + 1)); if (m_tileMapDefinitions[superTileCol] == null){ m_tileMapDefinitions[superTileCol] = new Array(); }; var tileMapDefinition:TileMapDefinition = m_tileMapDefinitions[superTileCol][superTileRow]; if (tileMapDefinition == null){ tileMapDefinition = new TileMapDefinition((superTileCol * m_columnsInSuperTile), (superTileRow * m_rowsInSuperTile)); tileMapDefinition.setSize(m_columnsInSuperTile, m_rowsInSuperTile); m_tileMapDefinitions[superTileCol][superTileRow] = tileMapDefinition; }; return (tileMapDefinition); } private function clickBack(a_event:Event):void{ dispatchEvent(new Event(Event.COMPLETE)); } private function selectTileLibrary(a_name:String):void{ var clickedLibraryPanel:TileLibraryPanel; if (m_entityLibraryPanel.visible){ m_entityLibraryPanel.visible = false; }; var i:int; while (i < m_tileLibraries.length) { clickedLibraryPanel = m_tileLibraries[i]; if (clickedLibraryPanel.name == a_name){ if (((!((m_activeTilePanel == null))) && ((m_activeTilePanel == clickedLibraryPanel)))){ clickedLibraryPanel.visible = !(clickedLibraryPanel.visible); } else { m_activeTilePanel = clickedLibraryPanel; clickedLibraryPanel.visible = true; setChildIndex(m_activeTilePanel, (this.numChildren - 1)); }; } else { clickedLibraryPanel.visible = false; }; i++; }; } private function recreateEngine():void{ cleanupEngine(); startEngine(); } private function addedToStage(a_event:Event):void{ var setName:String; var showLibraryButton:VistaButton; var tileLibraryPanel:TileLibraryPanel; this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage); m_background = new Sprite(); m_background.graphics.beginFill(0xE2E2E2); m_background.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight); addChildAt(m_background, 0); m_entityLibraryPanel = new EntityLibraryPanel(m_entityLibrary); m_entityLibraryPanel.addEventListener(Event.SELECT, selectEntity); m_entityLibraryPanel.visible = false; m_entityLibraryPanel.y = 60; addChild(m_entityLibraryPanel); var backButton:VistaButton = EditorButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.x = (this.stage.stageWidth - backButton.width); addChild(backButton); m_showEntityLibraryButton = EditorButtonFactory.instance.createButton("<u>E</u>ntities"); m_showEntityLibraryButton.addEventListener(MouseEvent.CLICK, clickShowEntityLibrary); addChild(m_showEntityLibraryButton); var setNames:Array = m_tileLibrary.getSetNames(); var buttonXPosition:Number = ((m_showEntityLibraryButton.x + m_showEntityLibraryButton.width) + 8); var s:int; while (s < setNames.length) { setName = setNames[s]; showLibraryButton = EditorButtonFactory.instance.createButton(((("<u>" + (s + 1)) + ".</u> ") + setName)); showLibraryButton.x = buttonXPosition; buttonXPosition = (buttonXPosition + showLibraryButton.width); showLibraryButton.name = setName; showLibraryButton.addEventListener(MouseEvent.CLICK, clickShowTileLibrary); addChild(showLibraryButton); m_tileSetButtons.push(showLibraryButton); tileLibraryPanel = new TileLibraryPanel(m_tileLibrary, setName); tileLibraryPanel.name = setName; tileLibraryPanel.addEventListener(Event.SELECT, selectTile); tileLibraryPanel.visible = false; tileLibraryPanel.y = 60; addChild(tileLibraryPanel); m_tileLibraries.push(tileLibraryPanel); s++; }; m_pixelSnappingPanel = new PixelSnappingPanel([(m_tileLibrary.tileWidth / 2), (m_tileLibraries.tileWidth / 4), 2, 1]); addChild(m_pixelSnappingPanel); m_pixelSnappingPanel.x = (this.stage.stageWidth - m_pixelSnappingPanel.width); m_pixelSnappingPanel.y = (this.stage.stageHeight - m_pixelSnappingPanel.height); m_pixelSnappingPanel.visible = false; m_tileDepthPanel = new TileDepthPanel(m_supportedDepths); addChild(m_tileDepthPanel); m_tileDepthPanel.x = (this.stage.stageWidth - m_tileDepthPanel.width); m_tileDepthPanel.y = (this.stage.stageHeight - m_tileDepthPanel.height); m_tileDepthPanel.visible = false; m_selectedIndicator = new TextField(); m_selectedIndicator.text = "()"; m_selectedIndicator.autoSize = "left"; m_selectedIndicator.mouseEnabled = false; m_selectedIndicator.y = (this.stage.stageHeight - m_selectedIndicator.height); addChild(m_selectedIndicator); m_columnsInSuperTile = Math.ceil((this.stage.stageWidth / m_tileLibrary.tileWidth)); m_rowsInSuperTile = Math.ceil((this.stage.stageHeight / m_tileLibrary.tileHeight)); } public function dispose():void{ trace("Implement LevelEditor.dispose"); } private function changeActiveTileToOneUnderMouse():void{ var tileLibrary:TileLibraryPanel; var tileCoords:Point = getTileCoordinatesUnderMouse(); var tileCol:int = tileCoords.x; var tileRow:int = tileCoords.y; var tileMapDefinition:TileMapDefinition = getTileMapDefinition(tileCol, tileRow); var localCol:int = (tileCol - tileMapDefinition.col); var localRow:int = (tileRow - tileMapDefinition.row); var newTileName:String = tileMapDefinition.getTileDefinition(localCol, localRow, m_tileDepthPanel.depth); if (newTileName == ""){ newTileName = "delete"; }; var i:int; while (i < m_tileLibraries.length) { tileLibrary = m_tileLibraries[i]; if (tileLibrary.hasTileType(newTileName)){ selectTileLibrary(tileLibrary.name); m_activeTilePanel.select(newTileName); m_activeTilePanel.visible = false; }; i++; }; } private function clickShowEntityLibrary(a_event:Event):void{ if (m_entityLibraryPanel.visible){ m_entityLibraryPanel.visible = false; return; }; if (m_activeTilePanel != null){ m_activeTilePanel.visible = false; m_activeTilePanel = null; }; hideAllPanels(); m_entityLibraryPanel.visible = true; } public function exportXML():XML{ var key:String; var p:int; var propertyXML:XML; var sr:int; var engineKey:String; var i:int; var spawnInfo:EntitySpawnInfo; var levelDef:LevelDefinition = m_engine.save(); var levelXML:XML = <level/> ; var properties:Array = []; var propertyDictionary:Dictionary = levelDef.getDataDump().dictionary; for (key in propertyDictionary) { propertyXML = <property/> ; propertyXML.@key = key; propertyXML.@value = propertyDictionary[key]; properties.push(propertyXML); }; p = 0; while (p < properties.length) { levelXML.appendChild(properties[p]); p++; }; var tmdXML:XML = TileMapDefinitionXMLFormat.toXML(m_tileMapDefinitions, m_superTileColCount, m_superTileRowCount, m_columnsInSuperTile, m_rowsInSuperTile); var spawnInfos:Array = levelDef.getSpawnInfos(); var sc:int; while (sc < m_superTileColCount) { sr = 0; while (sr < m_superTileRowCount) { engineKey = ((sc + "_") + sr); i = (spawnInfos.length - 1); while (i >= 0) { spawnInfo = spawnInfos[i]; if (spawnInfo.type == engineKey){ spawnInfos.splice(i, 1); }; i--; }; sr++; }; sc++; }; var entitiesXML:XML = EntityDefinitionXMLFormat.toXML(levelDef, m_entityLibrary); levelXML.appendChild(entitiesXML); levelXML.appendChild(tmdXML); return (levelXML); } private function getSuperTileRow(a_globalRow:int):int{ return (Math.floor((a_globalRow / m_rowsInSuperTile))); } private function processMouseUp(a_event:Event):void{ var type:String; this.stage.removeEventListener(MouseEvent.MOUSE_UP, processMouseUp, false); m_mouseDown = false; if (((!((m_activeTilePanel == null))) && (!((m_activeTilePanel.activeTileName == ""))))){ return; }; var mouseX:int = m_engine.renderer.mouseX; var mouseY:int = m_engine.renderer.mouseY; var mousePickedEntity:Entity = m_engine.pickEntity(mouseX, mouseY, true); if (((!((mousePickedEntity == null))) && (mousePickedEntity.properties.getBoolean("EDITOR_SELECTABLE", true)))){ if (m_lastEntity == mousePickedEntity){ m_lastEntity = null; }; m_previewObject.parent.removeChild(m_previewObject); m_previewObject = null; type = mousePickedEntity.entityTypeDefinition.type; m_propertiesOfLastPickedObject = mousePickedEntity.properties.clone(); trace(("Properties of selected object " + m_propertiesOfLastPickedObject)); m_engine.destroyEntity(mousePickedEntity.id); m_entityLibraryPanel.select(type); return; }; if (m_entityLibraryPanel.activeEntityName != ""){ processEntityClick(); }; } private function selectTile(a_event:Event):void{ m_propertiesOfLastPickedObject = null; m_tileMode = true; hideAllPanels(); m_tileDepthPanel.visible = true; } public function startEngine():void{ var renderWidth:int = this.stage.stageWidth; var renderHeight:int = this.stage.stageHeight; m_container = new Sprite(); addChildAt(m_container, 1); var renderer:EngineRenderer = new EngineRenderer(m_container, renderWidth, renderHeight, new DebugDraw()); var keyboardTemplate:KeyboardTemplate = new KeyboardTemplate(); keyboardTemplate.registerAction(KeyboardMap.LEFT, "Move left"); keyboardTemplate.registerAction(KeyboardMap.RIGHT, "Move right"); keyboardTemplate.registerAction(KeyboardMap.UP, "Move up"); keyboardTemplate.registerAction(KeyboardMap.DOWN, "Move down"); keyboardTemplate.registerAction(KeyboardMap.S, "Save"); keyboardTemplate.registerAction(KeyboardMap.T, "Stuffs"); keyboardTemplate.registerAction(KeyboardMap.E, "Entity Panel"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_1, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_2, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_3, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_4, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_5, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_6, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_7, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_8, "-"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_9, "-"); m_engine = new Engine(renderer, keyboardTemplate, false, true); m_engine.removeEventListener(EngineEvent.INITIALIZED, onInitialized, false); m_engine.addEventListener(EngineEvent.INITIALIZED, onInitialized, false, 0, true); m_engine.initialize(m_entityLibrary); } private function cleanupEngine():void{ } private function hideAllPanels():void{ m_tileDepthPanel.visible = false; m_entityLibraryPanel.visible = false; selectTileLibrary(""); } private function clickShowTileLibrary(a_event:Event):void{ var clickedTileSetButton:VistaButton = (a_event.currentTarget as VistaButton); selectTileLibrary(clickedTileSetButton.name); } private function processMouseDown(a_event:MouseEvent):void{ if (a_event.ctrlKey){ changeActiveTileToOneUnderMouse(); return; }; m_mouseDown = true; this.stage.addEventListener(MouseEvent.MOUSE_UP, processMouseUp, false, 0, true); } private function processTileClick():void{ if (!m_tileMode){ return; }; if (m_activeTilePanel == null){ return; }; var tileCoord:Point = getTileCoordinatesUnderMouse(); m_selectedIndicator.appendText(((((" tile[" + tileCoord.x) + ",") + tileCoord.y) + "]")); var tileCol:int = tileCoord.x; var tileRow:int = tileCoord.y; if ((((tileCol < 0)) || ((tileRow < 0)))){ trace("Can't have negative coordinates"); return; }; var tileMapDefinition:TileMapDefinition = getTileMapDefinition(tileCol, tileRow); var localCol:int = (tileCol - tileMapDefinition.col); var localRow:int = (tileRow - tileMapDefinition.row); var tileName:String = m_activeTilePanel.activeTileName; if (tileName == "delete"){ tileName = ""; }; if (tileMapDefinition.getTileDefinition(localCol, localRow, m_tileDepthPanel.depth) == tileName){ return; }; tileMapDefinition.setTileDefinition(localCol, localRow, tileName, m_tileDepthPanel.depth); var superTileCol:int = getSuperTileCol(tileCol); var superTileRow:int = getSuperTileRow(tileRow); var engineKey:String = ((superTileCol + "_") + superTileRow); m_engine.destroyEntity(engineKey); m_engine.removeEntityType(engineKey); var entityDef:EntityTypeDefinition = tileMapDefinition.createEntityTypeDefinition(m_tileLibrary, -1); entityDef.type = engineKey; m_engine.addEntityType(entityDef); m_engine.createEntity(new EntitySpawnInfo(engineKey, engineKey, ((m_tileLibrary.tileWidth * m_columnsInSuperTile) * superTileCol), ((m_tileLibrary.tileHeight * m_rowsInSuperTile) * superTileRow), 0, 0)); } private function onLoaded(a_event:Event):void{ m_engine.removeEventListener(EngineEvent.UPDATE, onUpdate, false); m_engine.addEventListener(EngineEvent.UPDATE, onUpdate, false, 0, true); m_background.removeEventListener(MouseEvent.MOUSE_DOWN, processMouseDown, false); m_background.addEventListener(MouseEvent.MOUSE_DOWN, processMouseDown, false, 0, true); m_container.removeEventListener(MouseEvent.MOUSE_DOWN, processMouseDown, false); m_container.addEventListener(MouseEvent.MOUSE_DOWN, processMouseDown, false, 0, true); m_engine.start(); } private function getTileCoordinatesUnderMouse():Point{ var mouseX:int = m_engine.renderer.mouseX; var mouseY:int = m_engine.renderer.mouseY; var tileCol:int = Math.floor((mouseX / m_tileLibrary.tileWidth)); var tileRow:int = Math.floor((mouseY / m_tileLibrary.tileHeight)); return (new Point(tileCol, tileRow)); } public function load(a_xml:XML):void{ m_levelXML = a_xml; recreateEngine(); } private function getSuperTileCol(a_globalCol:int):int{ return (Math.floor((a_globalCol / m_columnsInSuperTile))); } private function onInitialized(a_event:Event):void{ executeLoad(); } private function processEntityClick():void{ var mouseX:int = m_engine.renderer.mouseX; var mouseY:int = m_engine.renderer.mouseY; var snapSize:int = m_pixelSnappingPanel.snapSize; var snapTileX:int = Math.round((mouseX / snapSize)); var snapTileY:int = Math.round((mouseY / snapSize)); mouseX = (snapTileX * snapSize); mouseY = (snapTileY * snapSize); if ((((mouseX < 0)) || ((mouseY < 0)))){ return; }; var entityType:String = m_entityLibraryPanel.activeEntityName; if (entityType == ""){ return; }; trace("creating", entityType, m_propertiesOfLastPickedObject); m_engine.createEntity(new EntitySpawnInfo(entityType, "", mouseX, mouseY, 0, 0, 0, 1, m_propertiesOfLastPickedObject)); trace("Resetting properties"); m_propertiesOfLastPickedObject = null; } private function executeLoad():void{ var levelPropertiesList:XMLList; var propertyXML:XML; var worldBounds:Rectangle; var maxCol:int; var maxRow:int; var entityList:Array; var e:int; var key:String; var value:String; var entitySpawnInfo:EntitySpawnInfo; m_engine.removeEventListener(EngineEvent.LOAD, onLoaded, false); m_engine.addEventListener(EngineEvent.LOAD, onLoaded, false, 0, true); var levelDefinition:LevelDefinition = new LevelDefinition(); if (m_levelXML != null){ levelPropertiesList = m_levelXML.property; for each (propertyXML in levelPropertiesList) { key = propertyXML.@key; value = propertyXML.@value; levelDefinition.getDataDump().setString(key, value); }; worldBounds = TileMapDefinitionXMLFormat.toLevelDefinitionFromXML(m_engine, levelDefinition, m_tileLibrary, (m_levelXML.tileMap[0] as XML), -1); levelDefinition.setWorldBounds(worldBounds.x, worldBounds.y, worldBounds.width, worldBounds.height); maxCol = Math.floor((worldBounds.right / m_tileLibrary.tileWidth)); maxRow = Math.floor((worldBounds.bottom / m_tileLibrary.tileHeight)); m_columnsInSuperTile = Math.ceil((m_engine.renderer.renderWidth / m_tileLibrary.tileWidth)); m_rowsInSuperTile = Math.ceil((m_engine.renderer.renderHeight / m_tileLibrary.tileHeight)); m_superTileColCount = (getSuperTileCol((maxCol - 1)) + 1); m_superTileRowCount = (getSuperTileRow((maxRow - 1)) + 1); getTileMapDefinition((maxCol - 1), (maxRow - 1)); m_tileMapDefinitions = TileMapDefinitionXMLFormat.fromXML((m_levelXML.tileMap[0] as XML), m_columnsInSuperTile, m_rowsInSuperTile); entityList = EntityDefinitionXMLFormat.fromXML((m_levelXML.entities[0] as XML)); e = 0; while (e < entityList.length) { entitySpawnInfo = entityList[e]; levelDefinition.addSpawnInfo(entitySpawnInfo); e++; }; }; m_engine.load(levelDefinition); } private function selectEntity(a_event:Event):void{ m_tileMode = false; hideAllPanels(); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 158
//PixelSnappingPanel (com.urbansquall.prophet.tilemaps.editor.PixelSnappingPanel) package com.urbansquall.prophet.tilemaps.editor { import flash.events.*; import flash.display.*; import com.urbansquall.ui.*; public class PixelSnappingPanel extends Sprite { private var m_supportedSizes:Array; private var m_snapSize:int; private var m_buttons:Array; public function PixelSnappingPanel(a_snapSizes:Array){ var pixelSize:int; var optionButton:VistaButton; super(); m_buttons = []; m_supportedSizes = a_snapSizes; m_snapSize = m_supportedSizes[0]; var i:int; while (i < m_supportedSizes.length) { pixelSize = m_supportedSizes[i]; optionButton = EditorButtonFactory.instance.createButton((pixelSize + "px")); optionButton.name = (pixelSize + ""); optionButton.addEventListener(MouseEvent.CLICK, clickChangeSnapping); optionButton.y = (i * optionButton.height); optionButton.width = 40; addChild(optionButton); m_buttons.push(optionButton); i++; }; this.graphics.beginFill(0xCCFF00); this.graphics.drawRect(0, 0, width, height); this.graphics.endFill(); select(m_supportedSizes[3]); } public function get snapSize():int{ return (m_snapSize); } private function clickChangeSnapping(a_event:Event):void{ a_event.stopPropagation(); var size:int = parseInt((a_event.currentTarget as DisplayObject).name); select(size); } private function select(a_size:int):void{ var button:DisplayObject; var i:int; while (i < m_buttons.length) { button = m_buttons[i]; if (button.name == (a_size + "")){ button.alpha = 1; } else { button.alpha = 0.5; }; i++; }; m_snapSize = a_size; } } }//package com.urbansquall.prophet.tilemaps.editor
Section 159
//TileDepthPanel (com.urbansquall.prophet.tilemaps.editor.TileDepthPanel) package com.urbansquall.prophet.tilemaps.editor { import flash.events.*; import flash.display.*; import com.urbansquall.ui.*; public class TileDepthPanel extends Sprite { private var m_depth:int; private var m_supportedDepths:Array; private var m_buttons:Array; public function TileDepthPanel(a_snapSizes:Array){ var depth:int; var optionButton:VistaButton; super(); m_buttons = []; m_supportedDepths = a_snapSizes; m_depth = m_supportedDepths[0]; var i:int; while (i < m_supportedDepths.length) { depth = m_supportedDepths[i]; optionButton = EditorButtonFactory.instance.createButton(("L: " + depth)); optionButton.name = (depth + ""); optionButton.addEventListener(MouseEvent.CLICK, clickChangeDepth); optionButton.y = (i * optionButton.height); optionButton.width = 40; addChild(optionButton); m_buttons.push(optionButton); i++; }; this.graphics.beginFill(0xCCFF00); this.graphics.drawRect(0, 0, width, height); this.graphics.endFill(); select(m_supportedDepths[3]); } private function select(a_depth:int):void{ var button:DisplayObject; var i:int; while (i < m_buttons.length) { button = m_buttons[i]; if (button.name == (a_depth + "")){ button.alpha = 1; } else { button.alpha = 0.5; }; i++; }; m_depth = a_depth; } public function get depth():int{ return (m_depth); } private function clickChangeDepth(a_event:Event):void{ a_event.stopPropagation(); var size:int = parseInt((a_event.currentTarget as DisplayObject).name); select(size); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 160
//TileLibraryPanel (com.urbansquall.prophet.tilemaps.editor.TileLibraryPanel) package com.urbansquall.prophet.tilemaps.editor { import flash.events.*; import flash.display.*; import flash.text.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import flash.filters.*; public class TileLibraryPanel extends Sprite { private var m_setName:String; private var m_tileGraphics:Array; private var m_activeTileName:String;// = "" private var m_tileLibrary:TileLibrary; public function TileLibraryPanel(a_tileLibrary:TileLibrary, a_setName:String){ m_tileGraphics = []; super(); m_setName = a_setName; m_tileLibrary = a_tileLibrary; this.addEventListener(Event.ADDED_TO_STAGE, addedToStage); } public function hasTileType(a_typeType:String):Boolean{ var tileGraphic:Sprite; var i:int; while (i < m_tileGraphics.length) { tileGraphic = m_tileGraphics[i]; if (tileGraphic.name == a_typeType){ return (true); }; i++; }; return (false); } private function addedToStage(a_event:Event):void{ var tileGraphic:Sprite; var nameLabel:TextField; var tileDefinition:TileDefinition; var tileDefinitionBackgroundColor:uint; var row:int; var col:int; var bitmap:Bitmap; var noImageLabel:TextField; var padding:Number = 0; var entryWidth:Number = (m_tileLibrary.tileWidth + padding); var entryHeight:Number = (m_tileLibrary.tileHeight + padding); this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage); var tileGraphicContainer:Sprite = new Sprite(); addChild(tileGraphicContainer); var firstTileDefName:String = ""; var entriesPerRow:int = Math.floor((this.stage.stageWidth / entryWidth)); var entriesCount:int = m_tileLibrary.tileDefinitionCount; var i = -1; var t:int; while (t < entriesCount) { tileDefinition = m_tileLibrary.getIndexedTileDefinition(t); if (tileDefinition.setName != m_setName){ } else { i++; if (firstTileDefName == ""){ firstTileDefName = tileDefinition.name; }; tileGraphic = new Sprite(); EditorToolTip.attachToolTip(tileGraphic, tileDefinition.name); if (tileDefinition.simpleBitmapData != null){ bitmap = new Bitmap(tileDefinition.simpleBitmapData); bitmap.x = (padding / 2); bitmap.y = (padding / 2); tileGraphic.addChild(bitmap); } else { noImageLabel = new TextField(); noImageLabel.text = "n/a"; noImageLabel.autoSize = "left"; noImageLabel.selectable = false; tileGraphic.addChild(noImageLabel); }; buttonify(tileGraphic); tileDefinitionBackgroundColor = 0xC0C0C0; if ((i % 2) == 0){ tileDefinitionBackgroundColor = 0x808080; }; tileGraphic.name = tileDefinition.name; tileGraphic.addEventListener(MouseEvent.CLICK, clickTileDefinition); row = Math.floor((i / entriesPerRow)); col = Math.floor((i % entriesPerRow)); tileGraphic.x = (col * entryWidth); tileGraphic.y = (row * entryHeight); tileGraphicContainer.addChild(tileGraphic); m_tileGraphics.push(tileGraphic); }; t++; }; i++; tileGraphic = new Sprite(); buttonify(tileGraphic); tileGraphic.name = "delete"; EditorToolTip.attachToolTip(tileGraphic, tileGraphic.name); tileGraphic.graphics.beginFill(0xFF00FF); tileGraphic.graphics.drawRect(0, 0, entryWidth, entryHeight); tileGraphicContainer.addChild(tileGraphic); tileGraphic.addEventListener(MouseEvent.CLICK, clickTileDefinition, false, 100); row = Math.floor((i / entriesPerRow)); col = Math.floor((i % entriesPerRow)); tileGraphic.x = (col * entryWidth); tileGraphic.y = (row * entryHeight); m_tileGraphics.push(tileGraphic); var background:Sprite = new Sprite(); background.graphics.lineStyle(1); background.graphics.beginFill(0xFFFFFF); background.graphics.drawRect(0, 0, this.width, this.height); addChildAt(background, 0); selectTileDefinition(firstTileDefName); } private function selectTileDefinition(a_name:String):void{ m_activeTileName = a_name; } private function unglow(a_event:Event):void{ var button:DisplayObject = (a_event.currentTarget as DisplayObject); button.filters = []; } private function glow(a_event:Event):void{ var button:DisplayObject = (a_event.currentTarget as DisplayObject); button.filters = [new GlowFilter(0xFFFFFF, 1, 6, 6, 2, 1, true)]; button.parent.setChildIndex(button, (button.parent.numChildren - 1)); } private function clickTileDefinition(a_event:Event):void{ var tileDefName:String = (a_event.currentTarget as DisplayObject).name; selectTileDefinition(tileDefName); dispatchEvent(new Event(Event.SELECT)); } private function buttonify(a_displayObject:DisplayObject):void{ a_displayObject.addEventListener(MouseEvent.ROLL_OVER, glow, false, 0, true); a_displayObject.addEventListener(MouseEvent.ROLL_OUT, unglow, false, 0, true); } public function select(a_name:String):void{ selectTileDefinition(a_name); } public function get activeTileName():String{ return (m_activeTileName); } } }//package com.urbansquall.prophet.tilemaps.editor
Section 161
//EntityDefinitionXMLFormat (com.urbansquall.prophet.tilemaps.EntityDefinitionXMLFormat) package com.urbansquall.prophet.tilemaps { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.utils.*; import flash.utils.*; public class EntityDefinitionXMLFormat { public function EntityDefinitionXMLFormat(){ super(); } public static function toXML(a_levelDefinition:LevelDefinition, a_entityLibrary:GameDefinition):XML{ var spawnInfo:EntitySpawnInfo; var entityXML:XML; var archetype:EntityTypeDefinition; var archetypeProperties:KeyValueMap; var propertiesDictionary:Dictionary; var keys:Array; var key:String; var k:int; var property:XML; var result:XML = <entities/> ; var spawnInfos:Array = a_levelDefinition.getSpawnInfos(); var i:int; for (;i < spawnInfos.length;i++) { spawnInfo = spawnInfos[i]; entityXML = <entity/> ; entityXML.@x = int(spawnInfo.x); entityXML.@y = int(spawnInfo.y); entityXML.@type = spawnInfo.type; if (spawnInfo.properties != null){ archetype = a_entityLibrary.lookupEntityType(spawnInfo.type); if (archetype.properties.getBoolean("TILE_MAP", false)){ continue; }; archetypeProperties = archetype.properties; propertiesDictionary = spawnInfo.properties.dictionary; keys = []; for (key in propertiesDictionary) { keys.push(key); }; keys.sort(); k = 0; while (k < keys.length) { key = keys[k]; if (((archetypeProperties.exists(key)) && ((archetypeProperties.getString(key, "") == String(propertiesDictionary[key]))))){ } else { property = <property/> ; property.@key = key; property.@value = propertiesDictionary[key]; entityXML.appendChild(property); }; k++; }; }; result.appendChild(entityXML); }; return (result); } public static function fromXML(a_entitiesXML:XML):Array{ var entityXML:XML; var x:Number; var y:Number; var type:String; var properties:KeyValueMap; var propertyList:XMLList; var propertyXML:XML; var spawnInfo:EntitySpawnInfo; var key:String; var value:String; var result:Array = new Array(); var entitiesListXML:XMLList = a_entitiesXML.entity; for each (entityXML in entitiesListXML) { x = entityXML.@x; y = entityXML.@y; type = entityXML.@type; properties = new KeyValueMap(); propertyList = entityXML.property; for each (propertyXML in propertyList) { key = propertyXML.@key; value = propertyXML.@value; properties.setString(key, value); }; spawnInfo = new EntitySpawnInfo(type, "", x, y, 0, 0, 0, 1, properties); result.push(spawnInfo); }; return (result); } } }//package com.urbansquall.prophet.tilemaps
Section 162
//TileDefinition (com.urbansquall.prophet.tilemaps.TileDefinition) package com.urbansquall.prophet.tilemaps { import flash.display.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; public class TileDefinition { public var polyDef:PolygonDef;// = null public var simpleBitmapData:BitmapData;// = null public var setName:String;// = "" public var properties:KeyValueMap; public var vertices:Array; public var name:String;// = "never_set" public function TileDefinition(){ super(); vertices = []; properties = new KeyValueMap(); } } }//package com.urbansquall.prophet.tilemaps
Section 163
//TileMapDefinition (com.urbansquall.prophet.tilemaps.TileMapDefinition) package com.urbansquall.prophet.tilemaps { import flash.display.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import Box2D.Dynamics.*; public class TileMapDefinition { private var m_row:int;// = 0 private var m_col:int;// = 0 private var m_tileMap:Array;// = null public function TileMapDefinition(a_col:int=0, a_row:int=0){ super(); m_col = a_col; m_row = a_row; } public function get col():int{ return (m_col); } public function setSize(a_colCount:int, a_rowCount:int):void{ var existingColCount:int; var existingRowCount:int; if ((((a_colCount <= 0)) || ((a_rowCount <= 0)))){ throw (new Error("setSize must be positive")); }; var c:int; var r:int; var newTileMap:Array = new Array(); c = 0; while (c < a_colCount) { newTileMap.push(new Array()); r = 0; while (r < a_rowCount) { newTileMap[c][r] = null; r++; }; c++; }; if (m_tileMap != null){ existingColCount = m_tileMap.length; existingRowCount = m_tileMap[0].length; existingColCount = Math.min(existingColCount, newTileMap.length); existingRowCount = Math.min(existingRowCount, newTileMap[0].length); c = 0; while (c < existingColCount) { r = 0; while (r < existingRowCount) { newTileMap[c][r] = m_tileMap[c][r]; r++; }; c++; }; }; m_tileMap = newTileMap; } public function get rowCount():int{ if (m_tileMap == null){ return (-1); }; return (m_tileMap[0].length); } public function setTileDefinition(a_col:int, a_row:int, a_type:String, a_depth:int):void{ var layer:Layer; var l:int; var layers:Array; if (a_type == ""){ if (m_tileMap[a_col][a_row] == null){ return; }; layers = m_tileMap[a_col][a_row]; l = (layers.length - 1); while (l >= 0) { layer = layers[l]; if (layer.depth == a_depth){ layers.splice(l, 1); }; l--; }; if (m_tileMap[a_col][a_row].length <= 0){ delete m_tileMap[a_col][a_row]; }; return; }; layers = m_tileMap[a_col][a_row]; if (layers == null){ layers = new Array(); m_tileMap[a_col][a_row] = layers; } else { l = (layers.length - 1); while (l >= 0) { layer = layers[l]; if (layer.depth == a_depth){ layers.splice(l, 1); }; l--; }; }; layer = new Layer(a_type, a_depth); layers.push(layer); layers.sortOn("depth", Array.NUMERIC); } public function createEntityTypeDefinition(a_tileLibrary:TileLibrary, a_renderLayer:int):EntityTypeDefinition{ var c:int; var r:int; var entityDefinition:EntityTypeDefinition = new EntityTypeDefinition(); entityDefinition.fixed = true; entityDefinition.properties.setBoolean("EDITOR_SELECTABLE", false); entityDefinition.properties.setBoolean("TILE_MAP", true); entityDefinition.pruneType = PruneType.IMMUNE; entityDefinition.shapes = []; var staticTilesBitmapData:BitmapData = new BitmapData((a_tileLibrary.tileWidth * colCount), (a_tileLibrary.tileHeight * rowCount), true, 0); if (a_tileLibrary.drawDirection == TileLibrary.DRAW_DIRECTION_BOTTOM_TO_TOP){ c = 0; while (c < colCount) { r = (rowCount - 1); while (r >= 0) { readCell(c, r, entityDefinition, staticTilesBitmapData, a_tileLibrary); r--; }; c++; }; } else { c = 0; while (c < colCount) { r = 0; while (r < rowCount) { readCell(c, r, entityDefinition, staticTilesBitmapData, a_tileLibrary); r++; }; c++; }; }; var bodyDef:b2BodyDef = new b2BodyDef(); entityDefinition.physics = bodyDef; entityDefinition.graphics.push(new BitmapGraphicDefinition(a_renderLayer, "image", staticTilesBitmapData, false)); return (entityDefinition); } public function get colCount():int{ if (m_tileMap == null){ return (-1); }; return (m_tileMap.length); } public function getTileDepths(a_col:int, a_row:int):Array{ var layer:Layer; var result:Array = []; var layers:Array = m_tileMap[a_col][a_row]; if (layers == null){ return ([]); }; var l:int; while (l < layers.length) { layer = layers[l]; result.push(layer.depth); l++; }; return (result); } public function getTileTypes(a_col:int, a_row:int):Array{ var layer:Layer; var result:Array = []; var layers:Array = m_tileMap[a_col][a_row]; if (layers == null){ return ([]); }; var l:int; while (l < layers.length) { layer = layers[l]; result.push(layer.type); l++; }; return (result); } public function getTileDefinition(a_col:int, a_row:int, a_depth:int):String{ var layer:Layer; if (m_tileMap[a_col][a_row] == null){ return (""); }; var layers:Array = m_tileMap[a_col][a_row]; var l:int; while (l < layers.length) { layer = layers[l]; if (layer.depth == a_depth){ return (layer.type); }; l++; }; return (""); } private function convertVertices(a_array:Array, a_offsetX:Number, a_offsetY:Number):PolygonDef{ var x:Number; var y:Number; var polyDef:PolygonDef = new PolygonDef(); var i:int; while (i < a_array.length) { x = a_array[i]; y = a_array[(i + 1)]; polyDef.addVertex((a_offsetX + x), (a_offsetY + y)); i = (i + 2); }; return (polyDef); } public function get row():int{ return (m_row); } public function calculateBounds():Rectangle{ var r:int; var minimum:Point = new Point(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); var maximum:Point = new Point(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); var c:int; while (c < colCount) { r = 0; while (r < rowCount) { if (m_tileMap[c][r] == null){ } else { minimum.x = Math.min(minimum.x, c); maximum.x = Math.max(maximum.x, c); minimum.y = Math.min(minimum.y, r); maximum.y = Math.max(maximum.y, r); }; r++; }; c++; }; minimum.x = (minimum.x + col); maximum.x = (maximum.x + (col + 1)); minimum.y = (minimum.y + row); maximum.y = (maximum.y + (row + 1)); return (new Rectangle(minimum.x, minimum.y, (maximum.x - minimum.x), (maximum.y - minimum.y))); } public function fillNonOccupiedTiles(a_tileType:String, a_depth:int=0, a_fillWholeMap:Boolean=true):void{ var existingType:String; var c:int; var r:int; var maxCol:int; var maxRow:int; if (a_fillWholeMap){ maxCol = m_tileMap.length; maxRow = m_tileMap[0].length; } else { c = 0; while (c < colCount) { r = 0; while (r < rowCount) { existingType = getTileDefinition(c, r, a_depth); if (existingType == ""){ } else { maxCol = Math.max(maxCol, c); maxRow = Math.max(maxRow, r); }; r++; }; c++; }; maxCol++; maxRow++; }; c = 0; while (c < maxCol) { r = 0; while (r < maxRow) { existingType = getTileDefinition(c, r, a_depth); if (existingType == ""){ setTileDefinition(c, r, a_tileType, a_depth); }; r++; }; c++; }; } private function readCell(c:int, r:int, a_entityDefinition:EntityTypeDefinition, a_drawTarget:BitmapData, a_tileLibrary:TileLibrary):void{ var layer:Layer; var tileName:String; var tileDef:TileDefinition; var offsetX:int; var offsetY:int; var shape:ShapeDef; var tileBitmapData:BitmapData; var transform:Matrix; if (m_tileMap[c][r] == null){ return; }; var layers:Array = m_tileMap[c][r]; var l:int; while (l < layers.length) { layer = layers[l]; tileName = layer.type; tileDef = a_tileLibrary.lookupTileDefinition(tileName); if (tileDef == null){ throw (new Error((("No tile definition with name [" + tileName) + "]"))); }; offsetX = (a_tileLibrary.tileWidth * c); offsetY = (a_tileLibrary.tileHeight * r); shape = null; if (tileDef.vertices.length > 0){ shape = convertVertices(tileDef.vertices, offsetX, offsetY); }; if (shape != null){ shape.userData = tileDef; a_entityDefinition.shapes.push(shape); }; tileBitmapData = tileDef.simpleBitmapData; if (tileBitmapData != null){ transform = new Matrix(); transform.translate((c * a_tileLibrary.tileWidth), (r * a_tileLibrary.tileHeight)); a_drawTarget.draw(tileBitmapData, transform); }; l++; }; } } }//package com.urbansquall.prophet.tilemaps class Layer { public var type:String; public var depth:int; private function Layer(a_type:String, a_depth:int){ super(); type = a_type; depth = a_depth; } }
Section 164
//TileMapDefinitionXMLFormat (com.urbansquall.prophet.tilemaps.TileMapDefinitionXMLFormat) package com.urbansquall.prophet.tilemaps { import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.definitions.*; public class TileMapDefinitionXMLFormat { public function TileMapDefinitionXMLFormat(){ super(); } public static function toLevelDefinitionFromXML(a_engine:Engine, a_levelDefinition:LevelDefinition, a_tileLibrary:TileLibrary, a_tileMapXML:XML, a_renderLayer:int, a_fillTile:String=""):Rectangle{ var sr:int; var tileMapDefinition:TileMapDefinition; var tileMapBounds:Rectangle; var engineKey:String; var entityDef:EntityTypeDefinition; var minimum:Point = new Point(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); var maximum:Point = new Point(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); var tileWidth:int = a_tileLibrary.tileWidth; var tileHeight:int = a_tileLibrary.tileHeight; var columnsInSuperTile:int = Math.ceil((a_engine.renderer.renderWidth / tileWidth)); var rowsInSuperTile:int = Math.ceil((a_engine.renderer.renderHeight / tileHeight)); var a_tileMap:Array = TileMapDefinitionXMLFormat.fromXML(a_tileMapXML, columnsInSuperTile, rowsInSuperTile, a_fillTile); var superTileSize:Point = calculateSuperTileCounts(a_tileMapXML, columnsInSuperTile, rowsInSuperTile); var superTileColCount:int = superTileSize.x; var superTileRowCount:int = superTileSize.y; var sc:int; while (sc < superTileColCount) { sr = 0; while (sr < superTileRowCount) { if (a_tileMap[sc] == null){ } else { tileMapDefinition = a_tileMap[sc][sr]; if (tileMapDefinition == null){ } else { tileMapBounds = tileMapDefinition.calculateBounds(); minimum.x = Math.min(minimum.x, (tileMapBounds.left * tileWidth)); minimum.y = Math.min(minimum.y, (tileMapBounds.top * tileHeight)); maximum.x = Math.max(maximum.x, (tileMapBounds.right * tileWidth)); maximum.y = Math.max(maximum.y, (tileMapBounds.bottom * tileHeight)); engineKey = ((sc + "_") + sr); entityDef = tileMapDefinition.createEntityTypeDefinition(a_tileLibrary, a_renderLayer); entityDef.type = engineKey; a_engine.addEntityType(entityDef); a_levelDefinition.createSpawnInfo(engineKey, engineKey, ((tileWidth * columnsInSuperTile) * sc), ((tileHeight * rowsInSuperTile) * sr), 0, 0); }; }; sr++; }; sc++; }; var bounds:Rectangle = new Rectangle(minimum.x, minimum.y, (maximum.x - minimum.x), (maximum.y - minimum.y)); return (bounds); } public static function toXML(a_tileMap:Array, a_superTileColCount:int, a_superTileRowCount:int, a_columnsInSuperTile:int, a_rowsInSuperTile:int):XML{ var sr:int; var tileMapDefinition:TileMapDefinition; var localColCount:int; var localRowCount:int; var c:int; var r:int; var globalC:int; var globalR:int; var tile:XML; var types:Array; var depths:Array; var hasData:Boolean; var t:int; var type:String; var depth:int; var layer:XML; var result:XML = <tileMap/> ; var tileCount:int; var sc:int; while (sc < a_superTileColCount) { sr = 0; while (sr < a_superTileRowCount) { if (a_tileMap[sc] == null){ } else { tileMapDefinition = a_tileMap[sc][sr]; if (tileMapDefinition == null){ } else { localColCount = tileMapDefinition.colCount; localRowCount = tileMapDefinition.rowCount; c = 0; while (c < a_columnsInSuperTile) { r = 0; while (r < a_rowsInSuperTile) { globalC = (c + (sc * a_columnsInSuperTile)); globalR = (r + (sr * a_rowsInSuperTile)); tile = <tile/> ; tile.@col = globalC; tile.@row = globalR; types = tileMapDefinition.getTileTypes(c, r); depths = tileMapDefinition.getTileDepths(c, r); hasData = false; t = 0; while (t < types.length) { hasData = true; type = types[t]; depth = depths[t]; layer = <layer/> ; layer.@depth = depth; layer.@type = type; tile.appendChild(layer); t++; }; if (hasData){ tileCount++; result.appendChild(tile); }; r++; }; c++; }; }; }; sr++; }; sc++; }; trace(("Exported tiles:" + tileCount)); return (result); } public static function fromXML(a_tileMapXML:XML, a_maxColsPerTileMap:int, a_maxRowsPerTileMap:int, a_fillTile:String=""):Array{ var tile:XML; var globalCol:int; var globalRow:int; var superTileCol:int; var superTileRow:int; var tileMapDefinition:TileMapDefinition; var localCol:int; var localRow:int; var layerList:XMLList; var layer:XML; var type:String; var depth:int; var sc:int; var sr:int; var fillWholeTileMap:Boolean; var result:Array = new Array(); var superTileColCount:int; var superTileRowCount:int; var tileList:XMLList = a_tileMapXML.tile; for each (tile in tileList) { globalCol = tile.@col; globalRow = tile.@row; superTileCol = Math.floor((globalCol / a_maxColsPerTileMap)); superTileRow = Math.floor((globalRow / a_maxRowsPerTileMap)); superTileColCount = Math.max(superTileColCount, (superTileCol + 1)); superTileRowCount = Math.max(superTileRowCount, (superTileRow + 1)); if (result[superTileCol] == null){ result[superTileCol] = new Array(); }; tileMapDefinition = result[superTileCol][superTileRow]; if (tileMapDefinition == null){ tileMapDefinition = new TileMapDefinition((superTileCol * a_maxColsPerTileMap), (superTileRow * a_maxRowsPerTileMap)); result[superTileCol][superTileRow] = tileMapDefinition; tileMapDefinition.setSize(a_maxColsPerTileMap, a_maxRowsPerTileMap); }; localCol = (globalCol - tileMapDefinition.col); localRow = (globalRow - tileMapDefinition.row); layerList = tile.layer; for each (layer in layerList) { type = layer.@type; depth = parseInt(layer.@depth); tileMapDefinition.setTileDefinition(localCol, localRow, type, depth); }; }; if (a_fillTile != ""){ sc = 0; while (sc < superTileColCount) { sr = 0; while (sr < superTileRowCount) { tileMapDefinition = result[sc][sr]; if (tileMapDefinition == null){ tileMapDefinition = new TileMapDefinition((sc * a_maxColsPerTileMap), (sr * a_maxRowsPerTileMap)); result[sc][sr] = tileMapDefinition; tileMapDefinition.setSize(a_maxColsPerTileMap, a_maxRowsPerTileMap); tileMapDefinition.setTileDefinition((a_maxColsPerTileMap - 1), (a_maxRowsPerTileMap - 1), a_fillTile, 0); }; fillWholeTileMap = !((((sc == (superTileColCount - 1))) || ((sr == (superTileRowCount - 1))))); tileMapDefinition.fillNonOccupiedTiles(a_fillTile, 0, fillWholeTileMap); sr++; }; sc++; }; }; return (result); } public static function calculateSuperTileCounts(a_tileMapXML:XML, a_maxColsPerTileMap:int, a_maxRowsPerTileMap:int):Point{ var tile:XML; var globalCol:int; var globalRow:int; var superTileCol:int; var superTileRow:int; var result:Array = new Array(); var superTileColCount:int; var superTileRowCount:int; var tileList:XMLList = a_tileMapXML.tile; var tileCount:int; for each (tile in tileList) { tileCount++; globalCol = tile.@col; globalRow = tile.@row; superTileCol = Math.floor((globalCol / a_maxColsPerTileMap)); superTileRow = Math.floor((globalRow / a_maxRowsPerTileMap)); superTileColCount = Math.max(superTileColCount, (superTileCol + 1)); superTileRowCount = Math.max(superTileRowCount, (superTileRow + 1)); }; return (new Point(superTileColCount, superTileRowCount)); } } }//package com.urbansquall.prophet.tilemaps
Section 165
//TileShapeHelper (com.urbansquall.prophet.tilemaps.TileShapeHelper) package com.urbansquall.prophet.tilemaps { public class TileShapeHelper { public function TileShapeHelper(){ super(); } public static function createRampBottomLeft(a_tileWidth:Number, a_tileHeight:Number):Array{ var vertices:Array = new Array(); addVertices(vertices, 0, 0); addVertices(vertices, a_tileWidth, a_tileHeight); addVertices(vertices, 0, a_tileHeight); return (vertices); } public static function createRectangle(a_tileWidth:Number, a_tileHeight:Number, a_offsetX:Number=0, a_offsetY:Number=0):Array{ var vertices:Array = new Array(); addVertices(vertices, (0 + a_offsetX), (0 + a_offsetY)); addVertices(vertices, (a_tileWidth + a_offsetX), (0 + a_offsetY)); addVertices(vertices, (a_tileWidth + a_offsetX), (a_tileHeight + a_offsetY)); addVertices(vertices, (0 + a_offsetX), (a_tileHeight + a_offsetY)); return (vertices); } public static function createRampTopRight(a_tileWidth:Number, a_tileHeight:Number):Array{ var vertices:Array = new Array(); addVertices(vertices, 0, 0); addVertices(vertices, a_tileWidth, 0); addVertices(vertices, a_tileWidth, a_tileHeight); return (vertices); } private static function addVertices(a_vertices:Array, a_x:Number, a_y:Number):void{ a_vertices.push(a_x); a_vertices.push(a_y); } public static function createRampBottomRight(a_tileWidth:Number, a_tileHeight:Number):Array{ var vertices:Array = new Array(); addVertices(vertices, a_tileWidth, 0); addVertices(vertices, a_tileWidth, a_tileHeight); addVertices(vertices, 0, a_tileHeight); return (vertices); } public static function createRampTopLeft(a_tileWidth:Number, a_tileHeight:Number):Array{ var vertices:Array = new Array(); addVertices(vertices, 0, 0); addVertices(vertices, a_tileWidth, 0); addVertices(vertices, 0, a_tileHeight); return (vertices); } } }//package com.urbansquall.prophet.tilemaps
Section 166
//INodeCreator (com.urbansquall.prophet.ui.levelscreen.INodeCreator) package com.urbansquall.prophet.ui.levelscreen { public interface INodeCreator { function createNode(_arg1:int, _arg2:String):Node; } }//package com.urbansquall.prophet.ui.levelscreen
Section 167
//LevelNodeOutEvent (com.urbansquall.prophet.ui.levelscreen.LevelNodeOutEvent) package com.urbansquall.prophet.ui.levelscreen { import flash.events.*; public class LevelNodeOutEvent extends Event { private var m_index:int; public static const LEVEL_OUT:String = "level_out"; public function LevelNodeOutEvent(a_index:int){ super(LEVEL_OUT); m_index = a_index; } public function get index():int{ return (m_index); } override public function clone():Event{ return (new LevelNodeOutEvent(m_index)); } } }//package com.urbansquall.prophet.ui.levelscreen
Section 168
//LevelNodeOverEvent (com.urbansquall.prophet.ui.levelscreen.LevelNodeOverEvent) package com.urbansquall.prophet.ui.levelscreen { import flash.events.*; public class LevelNodeOverEvent extends Event { private var m_index:int; public static const LEVEL_OVER:String = "level_over"; public function LevelNodeOverEvent(a_index:int){ super(LEVEL_OVER); m_index = a_index; } public function get index():int{ return (m_index); } override public function clone():Event{ return (new LevelNodeOverEvent(m_index)); } } }//package com.urbansquall.prophet.ui.levelscreen
Section 169
//LevelSelectEvent (com.urbansquall.prophet.ui.levelscreen.LevelSelectEvent) package com.urbansquall.prophet.ui.levelscreen { import flash.events.*; public class LevelSelectEvent extends Event { private var m_index:int; public static const LEVEL_SELECT:String = "level_select"; public function LevelSelectEvent(a_index:int){ super(LEVEL_SELECT); m_index = a_index; } public function get index():int{ return (m_index); } override public function clone():Event{ return (new LevelSelectEvent(m_index)); } } }//package com.urbansquall.prophet.ui.levelscreen
Section 170
//LevelSelector (com.urbansquall.prophet.ui.levelscreen.LevelSelector) package com.urbansquall.prophet.ui.levelscreen { import flash.events.*; import flash.display.*; public class LevelSelector extends Sprite { private var m_nodes:Array; private var m_trailsOn:Boolean; private var m_nodeCreator:INodeCreator; private var m_levelCount:int; private var m_levelProgress:int; public function LevelSelector(a_levelProgress:int, a_levelCount:int, a_nodeCreator:INodeCreator){ super(); m_nodes = []; m_levelProgress = a_levelProgress; m_levelCount = a_levelCount; m_trailsOn = false; m_nodeCreator = a_nodeCreator; } private function drawTrails(a_x1:int, a_y1:int, a_x2:int, a_y2:int):void{ this.graphics.lineStyle(3, 0xFF); this.graphics.moveTo(a_x1, a_y1); this.graphics.curveTo((a_x1 + 10), (a_y1 + 10), a_x2, a_y2); } public function moveNode(a_nodeNumber:int, a_x:int, a_y:int):Boolean{ if (m_nodes[a_nodeNumber] == null){ return (false); }; m_nodes[a_nodeNumber].x = a_x; m_nodes[a_nodeNumber].y = a_y; return (true); } private function addNode():void{ var status:String; if (m_nodes.length < m_levelProgress){ status = Node.NODE_STATUS_FINISHED; } else { if (m_nodes.length == m_levelProgress){ status = Node.NODE_STATUS_UNLOCKED; } else { status = Node.NODE_STATUS_LOCKED; }; }; var newNode:Node = m_nodeCreator.createNode(m_nodes.length, status); if (status != Node.NODE_STATUS_LOCKED){ newNode.addEventListener(MouseEvent.CLICK, selectLevel); }; newNode.addEventListener(MouseEvent.MOUSE_OVER, overNode); newNode.addEventListener(MouseEvent.MOUSE_OUT, outOfNode); addChild(newNode); m_nodes.push(newNode); } private function outOfNode(a_event:MouseEvent):void{ var node:Node = (a_event.currentTarget as Node); var index:int = node.index; dispatchEvent(new LevelNodeOutEvent(index)); } public function selectLevel(a_event:MouseEvent):void{ var node:Node = (a_event.currentTarget as Node); var index:int = node.index; dispatchEvent(new LevelSelectEvent(index)); } public function buildNodeGrid(a_x:int, a_y:int, a_xCount:int, a_yCount:int):void{ var j:int; var index:int; var i:int; while (i < a_yCount) { j = 0; while (j < a_xCount) { addNode(); if (((true) || (((i % 2) == 0)))){ m_nodes[(m_nodes.length - 1)].x = (a_x + (j * 100)); } else { m_nodes[(m_nodes.length - 1)].x = ((a_x + -((j * 100))) + ((a_xCount - 1) * 100)); }; m_nodes[(m_nodes.length - 1)].y = (a_y + (i * 100)); if (((m_trailsOn) && ((j > 0)))){ drawTrails(m_nodes[(m_nodes.length - 1)].x, (m_nodes[(m_nodes.length - 1)].y + (m_nodes[(m_nodes.length - 1)].height / 2)), (m_nodes[(m_nodes.length - 2)].x + 10), (m_nodes[(m_nodes.length - 2)].y + 10)); }; index++; if (index >= m_levelCount){ return; }; j++; }; i++; }; } public function getNode(a_index:int):Node{ return (m_nodes[a_index]); } private function overNode(a_event:MouseEvent):void{ var node:Node = (a_event.currentTarget as Node); var index:int = node.index; dispatchEvent(new LevelNodeOverEvent(index)); } } }//package com.urbansquall.prophet.ui.levelscreen
Section 171
//Node (com.urbansquall.prophet.ui.levelscreen.Node) package com.urbansquall.prophet.ui.levelscreen { import flash.display.*; public class Node extends Sprite { private var m_index:int; private var m_status:String; private var m_unlockedAndNotFinishedGraphic:DisplayObject; private var m_lockedGraphic:DisplayObject; private var m_unlockedAndFinishedGraphic:DisplayObject; public static const NODE_STATUS_UNLOCKED:String = "unlocked"; public static const NODE_STATUS_FINISHED:String = "finished"; public static const NODE_STATUS_LOCKED:String = "locked"; public function Node(a_unlockedAndNotFinishedGraphic:DisplayObject, a_unlockedAndFinishedGraphic:DisplayObject, a_lockedGraphic:DisplayObject, a_status:String, a_index:int){ super(); m_index = a_index; m_unlockedAndNotFinishedGraphic = a_unlockedAndNotFinishedGraphic; m_unlockedAndFinishedGraphic = a_unlockedAndFinishedGraphic; m_lockedGraphic = a_lockedGraphic; addChild(m_unlockedAndNotFinishedGraphic); addChild(m_unlockedAndFinishedGraphic); addChild(m_lockedGraphic); m_status = a_status; updateImage(); if (m_status != NODE_STATUS_LOCKED){ buttonMode = true; }; } private function updateImage():void{ m_unlockedAndFinishedGraphic.visible = false; m_unlockedAndNotFinishedGraphic.visible = false; m_lockedGraphic.visible = false; switch (m_status){ case NODE_STATUS_LOCKED: m_lockedGraphic.visible = true; break; case NODE_STATUS_UNLOCKED: m_unlockedAndNotFinishedGraphic.visible = true; break; case NODE_STATUS_FINISHED: m_unlockedAndFinishedGraphic.visible = true; break; default: trace("default status"); throw (new Error("What is this?")); }; } public function get index():int{ return (m_index); } } }//package com.urbansquall.prophet.ui.levelscreen
Section 172
//FPS (com.urbansquall.prophet.utils.FPS) package com.urbansquall.prophet.utils { import flash.events.*; import flash.text.*; import flash.utils.*; public class FPS extends TextField { protected var timeOfLastUpdate:Number; protected var timer:Timer; protected var frames:int; public function FPS(){ super(); defaultTextFormat = new TextFormat("Verdana", 9, 0); timer = new Timer(1000); this.autoSize = TextFieldAutoSize.CENTER; this.text = "FPS"; this.backgroundColor = 0xFFFFFF; this.background = true; timer.addEventListener(TimerEvent.TIMER, timerHandler); addEventListener(Event.ENTER_FRAME, enterFrameHandler); timer.start(); timeOfLastUpdate = getTimer(); } private function timerHandler(e:TimerEvent):void{ var deltaTime:Number = calculateDeltaTime(); text = String(Math.round((frames / (deltaTime / 1000)))); frames = 0; } private function enterFrameHandler(e:Event):void{ frames++; } private function calculateDeltaTime():Number{ var currentTime:Number = getTimer(); var deltaTime:Number = (currentTime - timeOfLastUpdate); timeOfLastUpdate = currentTime; return (deltaTime); } public function reset():void{ frames = 0; text = "FPS"; timeOfLastUpdate = getTimer(); } } }//package com.urbansquall.prophet.utils
Section 173
//KeyValueMap (com.urbansquall.prophet.utils.KeyValueMap) package com.urbansquall.prophet.utils { import flash.utils.*; public class KeyValueMap { private var m_map:Dictionary; public function KeyValueMap(){ super(); m_map = new Dictionary(); } public function setObject(a_key:String, a_value:Object):void{ m_map[a_key] = a_value; } public function getString(a_key:String, a_defaultValue:String):String{ if (!exists(a_key)){ return (a_defaultValue); }; return (String(m_map[a_key])); } public function setNumber(a_key:String, a_value:Number):void{ m_map[a_key] = a_value; } public function setString(a_key:String, a_value:String):void{ m_map[a_key] = a_value; } public function get dictionary():Dictionary{ return (m_map); } public function exists(a_key:String):Boolean{ if (m_map[a_key] == null){ return (false); }; return (true); } public function clone():KeyValueMap{ var cloneMap:KeyValueMap = new KeyValueMap(); cloneMap.integrate(this.m_map); return (cloneMap); } public function kill(a_key:String):void{ delete m_map[a_key]; } public function dispose():void{ m_map = null; } public function hasBooleanValue(a_key:String, a_value:Boolean):Boolean{ if (!exists(a_key)){ return (false); }; return ((m_map[a_key] == a_value)); } public function setBoolean(a_key:String, a_value:Boolean):void{ m_map[a_key] = a_value; } public function toString():String{ var key:String; var result:String = "<KVM:"; for (key in m_map) { result = (result + (((("[" + key) + ":") + m_map[key]) + "]")); }; return (result); } public function setInt(a_key:String, a_value:int):void{ m_map[a_key] = a_value; } public function hasNumberValue(a_key:String, a_value:Number):Boolean{ if (!exists(a_key)){ return (false); }; return ((m_map[a_key] == a_value)); } public function integrate(a_dictionary:Dictionary):void{ var key:String; for (key in a_dictionary) { m_map[key] = a_dictionary[key]; }; } public function getBoolean(a_key:String, a_defaultValue:Boolean):Boolean{ if (!exists(a_key)){ return (a_defaultValue); }; var lowercaseVersion:String = String(m_map[a_key]).toLowerCase(); return ((((((lowercaseVersion == "t")) || ((lowercaseVersion == "true")))) || ((lowercaseVersion == "1")))); } public function getObject(a_key:String, a_defaultValue:Object):Object{ if (!exists(a_key)){ return (a_defaultValue); }; return (m_map[a_key]); } public function hasObjectValue(a_key:String, a_value:Object):Boolean{ if (!exists(a_key)){ return (false); }; return ((m_map[a_key] == a_value)); } public function getInt(a_key:String, a_defaultValue:int):int{ if (!exists(a_key)){ return (a_defaultValue); }; return (int(m_map[a_key])); } public function hasIntValue(a_key:String, a_value:int):Boolean{ if (!exists(a_key)){ return (false); }; return ((m_map[a_key] == a_value)); } public function hasStringValue(a_key:String, a_value:String):Boolean{ if (!exists(a_key)){ return (false); }; return ((m_map[a_key] == a_value)); } public function getNumber(a_key:String, a_defaultValue:Number):Number{ if (!exists(a_key)){ return (a_defaultValue); }; var number:Number = Number(m_map[a_key]); return (number); } } }//package com.urbansquall.prophet.utils
Section 174
//SafeSolManager (com.urbansquall.security.SafeSolManager) package com.urbansquall.security { import flash.events.*; import flash.utils.*; import flash.net.*; public class SafeSolManager { private var m_keys:Array; private var m_hexKey:uint; private var m_xorKey:int; private var m_so:SharedObject; public function SafeSolManager(a_name:String, a_hexKey:uint=16753249){ super(); m_so = SharedObject.getLocal(a_name); m_so.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); m_hexKey = a_hexKey; m_keys = []; if (m_so.data["ads"] == undefined){ m_so.data["ads"] = new Object(); }; if (readRealData(m_hexKey, int, false) == undefined){ m_xorKey = (Math.random() * int.MAX_VALUE); writeRealData(m_hexKey, m_xorKey, int, false); } else { m_xorKey = readRealData(m_hexKey, int, false); }; } private function hexStr(a_hex:uint):String{ return (a_hex.toString(16).toUpperCase()); } public function flush():void{ m_so.flush(); } public function readString(a_var:String):String{ return (read(a_var, String)); } public function writeNumber(a_var:String, a_value:Number):void{ write(a_var, a_value, Number); } public function clear():void{ m_so.clear(); } private function onNetStatus(a_event:NetStatusEvent):void{ if (a_event.info.code == "SharedObject.Flush.Failed"){ trace("Did not save, because the user didn't expand their storage space."); }; } public function createInt(a_var:String, a_value:int, a_hasFake:Boolean=false):void{ create(a_var, a_value, int, a_hasFake); } public function createBool(a_var:String, a_value:Boolean, a_hasFake:Boolean=false):void{ create(a_var, a_value, Boolean, a_hasFake); } public function writeString(a_var:String, a_value:String):void{ write(a_var, a_value, String); } private function readRealData(a_hexKey:uint, a_type:Class, a_isEncrypted:Boolean){ var bab:ByteArray; var ban:ByteArray; var bas:ByteArray; var j:int; var intBytes:int; var val:* = m_so.data["ads"][hexStr(a_hexKey)]; if (((!((val == undefined))) && (a_isEncrypted))){ if (a_type == int){ val = (val ^ m_xorKey); } else { if (a_type == Boolean){ bab = new ByteArray(); bab.writeInt((val ^ m_xorKey)); bab.position = 0; val = bab.readBoolean(); } else { if (a_type == Number){ ban = new ByteArray(); ban.writeInt((val ^ m_xorKey)); ban.position = 0; val = ban.readFloat(); } else { if (a_type == String){ bas = new ByteArray(); val.position = 0; j = 0; while (j < (val.length / 4)) { intBytes = val.readInt(); bas.writeInt((intBytes ^ m_xorKey)); j++; }; bas.position = 0; val = bas.readUTF(); }; }; }; }; }; return (val); } public function writeInt(a_var:String, a_value:int):void{ write(a_var, a_value, int); } public function readBool(a_var:String):Boolean{ return (read(a_var, Boolean)); } private function readFakeData(a_name:String){ return (m_so.data[a_name]); } public function createNumber(a_var:String, a_value:Number, a_hasFake:Boolean=false):void{ create(a_var, a_value, Number, a_hasFake); } private function write(a_var:String, a_value, a_type:Class):void{ var i:int = m_keys.indexOf(a_var); if (i < 0){ writeFakeData(a_var, a_value); return; }; var dictKey:uint = ((m_hexKey + i) + 1); writeRealData(dictKey, a_value, a_type, true); if (readFakeData(a_var) != undefined){ writeFakeData(a_var, a_value); }; } private function writeRealData(a_hexKey:uint, a_value, a_type:Class, a_isEncrypted:Boolean):void{ var bab:ByteArray; var ban:ByteArray; var bas:ByteArray; var i:int; var j:int; var bytes:int; var writeVal:int = a_value; if (a_isEncrypted){ if (a_type == int){ writeVal = (a_value ^ m_xorKey); } else { if (a_type == Boolean){ bab = new ByteArray(); bab.writeBoolean(a_value); bab.writeByte((Math.random() * 0xFF)); bab.writeByte((Math.random() * 0xFF)); bab.writeByte((Math.random() * 0xFF)); bab.position = 0; writeVal = (bab.readInt() ^ m_xorKey); } else { if (a_type == Number){ ban = new ByteArray(); ban.writeFloat(a_value); ban.position = 0; writeVal = (ban.readInt() ^ m_xorKey); } else { if (a_type == String){ bas = new ByteArray(); bas.writeUTF(a_value); i = (3 - (bas.length % 4)); while (i >= 0) { bas.writeByte((Math.random() * 0xFF)); i--; }; bas.position = 0; j = 0; while (j < (bas.length / 4)) { bytes = bas.readInt(); bas.position = (bas.position - 4); bas.writeInt((bytes ^ m_xorKey)); j++; }; m_so.data["ads"][hexStr(a_hexKey)] = bas; return; }; }; }; }; }; m_so.data["ads"][hexStr(a_hexKey)] = writeVal; } public function writeBool(a_var:String, a_value:Boolean):void{ write(a_var, a_value, Boolean); } public function createString(a_var:String, a_value:String, a_hasFake:Boolean=false):void{ create(a_var, a_value, String, a_hasFake); } private function writeFakeData(a_name:String, a_value):void{ m_so.data[a_name] = a_value; } private function read(a_var:String, a_type:Class){ var i:int = m_keys.indexOf(a_var); if (i < 0){ return (readFakeData(a_var)); }; var dictKey:uint = ((m_hexKey + i) + 1); return (readRealData(dictKey, a_type, true)); } public function readInt(a_var:String):int{ return (read(a_var, int)); } private function create(a_var:String, a_value, a_type:Class, a_hasFake:Boolean):void{ m_keys.push(a_var); var dictKey:uint = (m_hexKey + m_keys.length); if (readRealData(dictKey, a_type, true) != undefined){ return; }; writeRealData(dictKey, a_value, a_type, true); if (a_hasFake){ writeFakeData(a_var, a_value); }; } public function readNumber(a_var:String):Number{ return (read(a_var, Number)); } } }//package com.urbansquall.security
Section 175
//ToolTip (com.urbansquall.ui.ToolTip) package com.urbansquall.ui { import flash.events.*; import flash.display.*; public class ToolTip extends Sprite { private var m_target:DisplayObject; private static var s_activeToolTip:ToolTip = null; private static var s_stage:Stage = null; public function ToolTip(a_target:DisplayObject){ super(); m_target = a_target; m_target.addEventListener(MouseEvent.MOUSE_OVER, showToolTip, false, 0, true); m_target.addEventListener(Event.REMOVED_FROM_STAGE, handleTargetRemoved); this.visible = false; this.mouseChildren = false; this.mouseEnabled = false; } private function fadeOut(a_event:Event):void{ this.alpha = (this.alpha - 0.03); if (this.alpha < 0.1){ removeEventListener(Event.ENTER_FRAME, fadeOut); this.visible = false; s_activeToolTip = null; }; } private function showToolTip(a_event:MouseEvent):void{ if (this.stage == null){ return; }; if (s_activeToolTip != null){ s_activeToolTip.hide(); }; removeEventListener(Event.ENTER_FRAME, fadeOut); this.visible = true; this.alpha = 1; this.x = this.stage.mouseX; this.y = this.stage.mouseY; if ((this.x + this.width) > stage.stageWidth){ this.x = (this.x - ((this.stage.mouseX + this.width) - stage.stageWidth)); }; this.parent.setChildIndex(this, (this.parent.numChildren - 1)); addEventListener(Event.ENTER_FRAME, tick, false, 0, true); s_activeToolTip = this; } private function handleTargetRemoved(a_event:Event):void{ this.parent.removeChild(this); removeEventListener(Event.ENTER_FRAME, tick); removeEventListener(Event.ENTER_FRAME, fadeOut); m_target.removeEventListener(Event.REMOVED_FROM_STAGE, handleTargetRemoved); m_target.removeEventListener(MouseEvent.MOUSE_OVER, showToolTip); m_target = null; } private function hide():void{ removeEventListener(Event.ENTER_FRAME, tick); removeEventListener(Event.ENTER_FRAME, fadeOut); this.visible = false; } private function tick(a_event:Event):void{ if (((!(this.hitTestPoint(this.stage.mouseX, this.stage.mouseY, true))) && (!(m_target.hitTestPoint(this.stage.mouseX, this.stage.mouseY, true))))){ addEventListener(Event.ENTER_FRAME, fadeOut, false, 0, true); removeEventListener(Event.ENTER_FRAME, tick); }; } public static function initialize(a_stage:Stage):void{ s_stage = a_stage; } public static function attachToolTip(a_target:DisplayObject, a_toolTipContents:DisplayObject):void{ if (s_stage == null){ throw (new Error("Call ToolTip.initialize at the start of your app before you call attachToolTip")); }; var toolTip:ToolTip = new ToolTip(a_target); toolTip.addChild(a_toolTipContents); s_stage.addChild(toolTip); } } }//package com.urbansquall.ui
Section 176
//VistaButton (com.urbansquall.ui.VistaButton) package com.urbansquall.ui { import flash.display.*; import flash.geom.*; import flash.text.*; import com.urbansquall.display.*; import flash.filters.*; public class VistaButton extends SimpleButton { private var m_over:VistaButtonState; private var m_down:VistaButtonState; private var m_factory:VistaButtonFactory; private var m_up:VistaButtonState; public function VistaButton(a_factory:VistaButtonFactory, a_title:String, a_iconClass:Class=null, a_description:String=null){ var a_factory = a_factory; var a_title = a_title; var a_iconClass = a_iconClass; var a_description = a_description; m_factory = a_factory; m_up = new VistaButtonState(); m_up.bg = new Tile9(m_factory.tile9Data); m_up.overlay = new Bitmap(m_factory.buttonOverlay); m_up.title = createHeading(a_title); m_up.image.filters = [new DropShadowFilter(2, 45, 0, 1, 4, 4, 1, 1)]; m_over = new VistaButtonState(); m_over.bg = new Tile9(m_factory.tile9Data); m_over.overlay = new Bitmap(m_factory.buttonOverlay); m_over.title = createHeading(a_title); m_over.image.transform.colorTransform = new ColorTransform(1.1, 1.1, 1.1); m_over.image.filters = [new DropShadowFilter(2, 45, 0, 1, 4, 4, 1, 1)]; m_down = new VistaButtonState(); m_down.bg = new Tile9(m_factory.tile9Data); m_down.overlay = new Bitmap(m_factory.buttonOverlay); m_down.title = createHeading(a_title); m_down.image.x = 1; m_down.image.y = 1; m_down.image.transform.colorTransform = new ColorTransform(1.05, 1.05, 1.05); m_down.image.filters = [new DropShadowFilter(3, 45, 0, 1, 4, 4, 1, 1, true)]; if (a_iconClass != null){ m_up.icon = new (a_iconClass); m_over.icon = new (a_iconClass); m_down.icon = new (a_iconClass); //unresolved jump var _slot1 = e; m_up.wrapIcon(a_iconClass); m_over.wrapIcon(a_iconClass); m_down.wrapIcon(a_iconClass); //unresolved jump var _slot1 = e; m_up.wrapIcon(a_iconClass, true); m_over.wrapIcon(a_iconClass, true); m_down.wrapIcon(a_iconClass, true); }; if (a_description != null){ m_up.description = createDescription(a_description); m_over.description = createDescription(a_description); m_down.description = createDescription(a_description); }; super(m_up.image, m_over.image, m_down.image, m_up.image); this.width = m_factory.defaultWidth; this.height = m_factory.defaultHeight; } private function createDescription(a_text:String):TextField{ var description:TextField = m_factory.createDescriptionTextField(); description.htmlText = a_text; return (description); } private function createHeading(a_text:String):TextField{ var header:TextField = m_factory.createHeaderTextField(); header.htmlText = (("<body><p align=\"center\">" + a_text) + "</p></body>"); return (header); } override public function get height():Number{ return (m_up.height); } override public function set height(a_height:Number):void{ m_up.height = a_height; m_over.height = a_height; m_down.height = a_height; } override public function get width():Number{ return (m_up.width); } override public function set width(a_width:Number):void{ m_up.width = a_width; m_over.width = a_width; m_down.width = a_width; } } }//package com.urbansquall.ui
Section 177
//VistaButtonFactory (com.urbansquall.ui.VistaButtonFactory) package com.urbansquall.ui { import flash.display.*; import flash.text.*; import com.urbansquall.display.*; public class VistaButtonFactory { private var m_tile9Data:Tile9Data; private var m_textColor:uint; private var m_buttonOverlay:BitmapData; private var m_defaultHeight:int; private var m_defaultWidth:int; private var m_descriptionColor:uint; public function VistaButtonFactory(a_textColor:uint, a_descriptionColor:uint, a_defaultWidth:int, a_defaultHeight:int, a_tile9Data:Tile9Data, a_buttonOverlay:BitmapData){ super(); m_textColor = a_textColor; m_descriptionColor = a_descriptionColor; m_defaultWidth = a_defaultWidth; m_defaultHeight = a_defaultHeight; m_tile9Data = a_tile9Data; m_buttonOverlay = a_buttonOverlay; } public function get defaultWidth():int{ return (m_defaultWidth); } public function createHeaderTextField():TextField{ var textfield:TextField = new TextField(); textfield.selectable = false; textfield.mouseEnabled = false; textfield.textColor = m_textColor; return (textfield); } public function createDescriptionTextField():TextField{ var textfield:TextField; textfield = new TextField(); textfield.selectable = false; textfield.mouseEnabled = false; textfield.textColor = m_descriptionColor; return (textfield); } public function get defaultHeight():int{ return (m_defaultHeight); } public function createButton(a_title:String, a_iconClass:Class=null, a_description:String=null):VistaButton{ return (new VistaButton(this, a_title, a_iconClass, a_description)); } public function get tile9Data():Tile9Data{ return (m_tile9Data); } public function get buttonOverlay():BitmapData{ return (m_buttonOverlay); } } }//package com.urbansquall.ui
Section 178
//VistaButtonState (com.urbansquall.ui.VistaButtonState) package com.urbansquall.ui { import flash.display.*; import flash.text.*; import flash.filters.*; class VistaButtonState { private var m_hardHeight:Number; private var m_title:TextField; private var m_hardWidth:Number; private var m_icon:Sprite; private var m_bg:Sprite; public var image:Sprite; private var m_description:TextField; private var m_usingIconWrap:Boolean; private var m_overlay:Sprite; private static const PADDING:int = 6; private static const FILTER_COLOR:uint = 10515817; function VistaButtonState(){ super(); image = new Sprite(); m_hardWidth = 130; m_hardHeight = 36; m_usingIconWrap = false; } public function get description():TextField{ return (m_description); } public function get bg():Sprite{ return (m_bg); } public function set bg(a_bg:Sprite):void{ m_bg = a_bg; image.addChild(m_bg); } public function get width():Number{ return (m_hardWidth); } public function set height(a_height:Number):void{ m_hardHeight = a_height; if (m_bg != null){ m_bg.height = m_hardHeight; }; updateDimensions(); } public function set width(a_width:Number):void{ m_hardWidth = a_width; if (m_bg != null){ m_bg.width = m_hardWidth; }; updateDimensions(); } public function get title():TextField{ return (m_title); } public function set overlay(a_overlay:Bitmap):void{ m_overlay = new Sprite(); m_overlay.addChild(a_overlay); image.addChild(m_overlay); } public function wrapIcon(a_iconClass:Class, a_needsParams:Boolean=false):void{ m_usingIconWrap = true; this.icon = new Sprite(); if (a_needsParams){ this.icon.addChild(new Bitmap(new a_iconClass(0, 0))); } else { this.icon.addChild(new (a_iconClass)); }; } public function get height():Number{ return (m_hardHeight); } public function set title(a_title:TextField):void{ if (m_title != null){ image.removeChild(m_title); }; m_title = a_title; m_title.autoSize = TextFieldAutoSize.CENTER; m_title.wordWrap = true; var f:TextFormat = m_title.defaultTextFormat; f = new TextFormat(f.font, f.size, f.color, f.bold, f.italic, f.underline, f.url, f.target, f.align, f.leftMargin, f.rightMargin, f.indent, f.leading); f.align = TextFormatAlign.CENTER; m_title.defaultTextFormat = f; m_title.htmlText = (("<body><p align=\"center\">" + m_title.htmlText) + "</p></body>"); m_title.filters = [new DropShadowFilter(2, 90, FILTER_COLOR, 0.75, 3, 3)]; image.addChild(m_title); updateDimensions(); } public function set icon(a_icon:Sprite):void{ if (m_icon != null){ image.removeChild(m_icon); }; m_icon = a_icon; m_icon.x = PADDING; image.addChild(m_icon); updateDimensions(); } public function set description(a_desc:TextField):void{ if (m_description != null){ image.removeChild(m_description); }; m_description = a_desc; m_description.wordWrap = true; image.addChild(m_description); updateDimensions(); } public function get icon():Sprite{ return (m_icon); } private function updateDimensions():void{ var combinedHeight:Number; if (m_overlay != null){ m_overlay.width = (m_hardWidth - 2); m_overlay.height = (m_hardHeight - 2); m_overlay.x = 1; m_overlay.y = 1; }; if (m_icon != null){ m_icon.scaleX = 1; m_icon.scaleY = 1; if (!m_usingIconWrap){ m_icon.scaleY = ((m_hardHeight - ((PADDING * 2) - 2)) / m_icon.height); m_icon.scaleX = m_icon.scaleY; }; m_icon.y = ((m_hardHeight - m_icon.height) / 2); m_title.x = (m_icon.width + (PADDING * 2)); m_title.width = ((m_hardWidth - m_title.x) - PADDING); } else { m_title.width = (m_hardWidth - 2); m_title.x = ((m_hardWidth - m_title.width) / 2); }; if (m_description == null){ m_title.y = (((m_hardHeight - m_title.height) / 2) - 2); } else { m_description.x = m_title.x; m_description.width = m_title.width; m_description.height = ((m_hardHeight - m_description.y) - PADDING); combinedHeight = (m_title.height + m_description.height); m_title.y = (((m_hardHeight - combinedHeight) / 2) - 2); m_description.y = (m_title.y + m_title.height); }; } } }//package com.urbansquall.ui
Section 179
//StringUtils (com.urbansquall.utils.StringUtils) package com.urbansquall.utils { public class StringUtils { public function StringUtils(){ super(); } public static function parseBBCode(a_message:String):String{ a_message = a_message.replace(/\[b\](.*?)\[\/b\]/gi, "<b>$1</b>"); a_message = a_message.replace(/\[i\](.*?)\[\/i\]/gi, "<i>$1</i>"); a_message = a_message.replace(/\[u\](.*?)\[\/u\]/gi, "<u>$1</u>"); a_message = a_message.replace(/\[color=(.*?)\](.*?)\[\/color\]/gi, "<font color=\"$1\">$2</font>"); return (a_message); } public static function trim(a_string:String):String{ return ((a_string) ? a_string.replace(/^\s+|\s+$/, "") : ""); } public static function convertToCurrency(a_number:Number):String{ var start:int; var intNumStr:String; var i:int; var intNum:String = Math.floor(a_number).toString(); var decNum:String = (Math.round(((a_number - Math.floor(a_number)) * 100)) / 100).toString(); var digitCount = 3; if (a_number < 0){ digitCount = (digitCount + 1); }; if (intNum.length > digitCount){ start = (intNum.length % 3); if (start){ intNumStr = (intNum.substr(0, start) + ","); } else { intNumStr = ""; }; i = start; while (i < (intNum.length - 3)) { intNumStr = (intNumStr + (intNum.substr(i, 3) + ",")); i = (i + 3); }; intNumStr = (intNumStr + intNum.substr(-3, 3)); } else { intNumStr = intNum; }; while (decNum.length < 4) { decNum = (decNum + "0"); }; decNum = decNum.substr(-2, 2); if (decNum == "00"){ return (intNumStr); }; return (((intNumStr + ".") + decNum)); } public static function parseURLs(a_message:String, a_targetWindow:String="_new"):String{ var protocol:String = "(http://)"; var urlPart:String = "([a-z0-9_-]+.[a-z0-9_-]+.[a-z0-9_-]+)"; var urlPattern:RegExp = new RegExp((protocol + urlPart), "ig"); a_message = a_message.replace(urlPattern, "<a href=\"http://$2\"><u>$1$2</u></a>"); var urlPart2:String = " (www.[a-z0-9_-]+.[a-z0-9_-]+)"; var urlPattern2:RegExp = new RegExp(urlPart2, "ig"); a_message = a_message.replace(urlPattern2, "<a href=\"http://$1\"><u>$1</u></a>"); return (a_message); } public static function trimLeft(a_string:String):String{ if (a_string == null){ return (""); }; return (a_string.replace(/^\s+/, "")); } public static function trimRight(a_string:String):String{ if (a_string == null){ return (""); }; return (a_string.replace(/\s+$/, "")); } public static function convertToClockTime(a_milliseconds:int):String{ var minutes:int = Math.floor(((a_milliseconds / 1000) / 60)); var seconds:int = (Math.floor((a_milliseconds / 1000)) % 60); minutes = Math.max(0, minutes); seconds = Math.max(0, seconds); var minutesString:String = ((minutes < 10)) ? ("0" + minutes) : String(minutes); var secondsString:String = ((seconds < 10)) ? ("0" + seconds) : String(seconds); var result:String = ((minutes + ":") + secondsString); return (result); } public static function parseBBCodeUrl(a_message:String):String{ a_message = a_message.replace(/\[url=(.*?)\](.*?)\[\/url\]/gi, "<a href=\"$1\" target=\"_blank\"><u>$2</u></a>"); return (a_message); } } }//package com.urbansquall.utils
Section 180
//AirDownAttackBehavior (game.behaviors.AirDownAttackBehavior) package game.behaviors { import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; import game.*; public class AirDownAttackBehavior extends Behavior { private var m_animationPlayer:AnimationPlayer;// = null private var m_triggered:Boolean;// = false private var m_attackShape:b2Shape; private static const ATTACK_HEIGHT:Number = 40; private static const ATTACK_WIDTH:Number = 40; public function AirDownAttackBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } private function onTouch(a_touchEvent:TouchEvent):void{ var player:Entity; var container:DisplayObjectContainer; if (m_triggered){ return; }; if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity == null){ return; }; if (!a_touchEvent.theirEntity.properties.getBoolean("isEnemy", false)){ return; }; if (m_attackShape == a_touchEvent.myShape){ m_triggered = true; player = entity.getEngine().lookupEntity("my_player"); player.properties.setBoolean("shellAttacking", false); AttackManager.turtleAttack(player, a_touchEvent.theirEntity, false, false); player.setVelocity(player.getVelocity().x, -250); player.properties.setNumber("invincibleTimer", 1500); container = entity.getEngine().renderer.lookupRenderLayer((Constants.ENTITY_DEFAULT_RENDER_LAYER + 10)); Effects.drawTurtleAttackEffect(a_touchEvent.position.x, a_touchEvent.position.y, container, 5); m_animationPlayer.play("falling"); }; } override public function tick(a_interval:Number):void{ var attackShape:CircleDef; var shapeDef:b2ShapeDef; if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (m_animationPlayer.currentAnimationID.indexOf("shellattack") >= 0){ if (m_attackShape == null){ m_triggered = false; attackShape = new CircleDef(); attackShape.friction = 0; attackShape.restitution = 0; attackShape.density = 1; attackShape.isSensor = true; attackShape.localPosition.y = 10; attackShape.radius = 30; shapeDef = attackShape.createBox2DShape(Dynamics.SCALE); m_attackShape = entity.body.CreateShape(shapeDef); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch, false, 0, true); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch, false, 0, true); this.entity.properties.setBoolean("isInvincible", true); SoundSystem.instance.playSound(new ShellAttack(), 0.8); }; } else { if (m_attackShape != null){ entity.body.DestroyShape(m_attackShape); m_attackShape = null; this.entity.removeEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.removeEventListener(EngineEvent.PERSIST_TOUCH, onTouch); this.entity.properties.setBoolean("isInvincible", false); }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 181
//AntiGravityBehavior (game.behaviors.AntiGravityBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class AntiGravityBehavior extends Behavior { private var yPosition:Number;// = 0 public function AntiGravityBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); yPosition = entity.getSpawnInfo().y; } override public function tick(a_deltaTime:Number):void{ entity.setPosition(entity.getPosition().x, yPosition); entity.setVelocity(entity.getVelocity().x, 0); } override public function dispose():void{ } } }//package game.behaviors
Section 182
//BreakableWallBehavior (game.behaviors.BreakableWallBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.utils.*; public class BreakableWallBehavior extends Behavior { private var m_playedDeathSound:Boolean;// = false private var m_animator:AnimationPlayer; public function BreakableWallBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } override public function tick(a_deltaTime:Number):void{ var animation:String; if (m_animator == null){ m_animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (this.entity.properties.getInt("lives", 1) <= 1){ if (!m_playedDeathSound){ m_playedDeathSound = true; SoundSystem.instance.playSound(new BreakableWall()); }; return; } else { if (this.entity.properties.getInt("lives", 1) <= 300){ animation = "damaged-3"; } else { if (this.entity.properties.getInt("lives", 1) <= 600){ animation = "damaged-2"; } else { if (this.entity.properties.getInt("lives", 1) < 900){ animation = "damaged-1"; } else { animation = "idle"; }; }; }; }; if (m_animator.currentAnimationID != animation){ m_animator.play(animation); }; } override public function dispose():void{ } } }//package game.behaviors
Section 183
//ChargeSpecialItemBehavior (game.behaviors.ChargeSpecialItemBehavior) package game.behaviors { import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class ChargeSpecialItemBehavior extends Behavior { private var m_collected:Boolean;// = false public var chargeAmount:int;// = 2 public function ChargeSpecialItemBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); chargeAmount = a_data.getInt("chargeAmount", chargeAmount); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var newOoze:int; if (m_collected){ return; }; var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (a_touchEvent.theirShape.IsSensor()){ return; }; var theirEntity:Entity = a_touchEvent.theirEntity; if (theirEntity.properties.getBoolean("isTurtle", false)){ m_collected = true; newOoze = theirEntity.properties.getInt("ooze", Constants.STARTING_CHARGE); newOoze = (newOoze + chargeAmount); if (newOoze > Constants.STARTING_CHARGE){ newOoze = Constants.STARTING_CHARGE; }; theirEntity.properties.setInt("ooze", newOoze); entity.getEngine().destroyEntity(entity.id); SoundSystem.instance.playSound(SoundCache.oozeSound); }; } override public function dispose():void{ } } }//package game.behaviors
Section 184
//CombatWaveBehavior (game.behaviors.CombatWaveBehavior) package game.behaviors { import shared.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.definitions.*; import game.events.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; import flash.utils.*; import Box2D.Dynamics.*; public class CombatWaveBehavior extends Behavior { private var m_delayBetweenWavesTimer:Number;// = 0 private var m_waveIndex:int;// = 0 private var m_delayedSpawns:Array; private var m_waves:Array; public var waveBoxWidth:Number; public var delayBetweenWaves:Number;// = 1500 public var waveBoxHeight:Number; private var spawnOffsetY:Number;// = 0 public var winOnDefeat:Boolean;// = true private var m_started:Boolean;// = false private var m_aliveTime:Dictionary; private var m_activeEntityIDs:Array; private var m_activated:Boolean;// = false private static const LEFT_WALL:int = -1; private static const RIGHT_WALL:int = 1; private static const BOUNDARY_THICKNESS:Number = 220; public function CombatWaveBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ var wave:Wave; var keyPrefix:String; var typeKey:String; var sideKey:String; var positionYKey:String; var velocityKey:String; var delayKey:String; var type:String; var side:String; var positionY:Number; var delay:Number; var velocityString:String; var velocity:Array; var vx:Number; var vy:Number; m_activeEntityIDs = []; m_aliveTime = new Dictionary(); m_delayedSpawns = []; waveBoxHeight = (2 * Constants.RENDER_HEIGHT); waveBoxWidth = Constants.RENDER_WIDTH; super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); m_waves = []; var properties:KeyValueMap = entity.properties; if (properties.exists("spawnOffsetY")){ spawnOffsetY = properties.getNumber("spawnOffsetY", 0); }; if (properties.exists("winOnDefeat")){ winOnDefeat = properties.getBoolean("winOnDefeat", true); }; var waveIndex:int; var enemyIndex:int; while (true) { wave = null; while (true) { keyPrefix = ((("wave_" + waveIndex) + "_e") + enemyIndex); typeKey = (keyPrefix + "_type"); if (!properties.exists(typeKey)){ break; }; if (wave == null){ wave = new Wave(); }; sideKey = (keyPrefix + "_side"); positionYKey = (keyPrefix + "_positionY"); velocityKey = (keyPrefix + "_velocity"); delayKey = (keyPrefix + "_delay"); type = properties.getString(typeKey, ""); side = properties.getString(sideKey, "right"); positionY = properties.getNumber(positionYKey, 0); delay = properties.getNumber(delayKey, 0); velocityString = properties.getString(velocityKey, "0 0"); velocity = velocityString.split(" "); vx = velocity[0]; vy = velocity[1]; wave.addSpawn(positionY, type, ((side.toLowerCase().charAt(0))=="l") ? LEFT_WALL : RIGHT_WALL, vx, vy, delay); enemyIndex++; }; if ((((wave == null)) || ((wave.spawns.length == 0)))){ break; }; m_waves.push(wave); waveIndex++; enemyIndex = 0; }; } private function calculateWaveBounds():Rectangle{ return (new Rectangle((this.entity.getPosition().x - (waveBoxWidth / 2)), (this.entity.getPosition().y - (waveBoxHeight / 2)), waveBoxWidth, waveBoxHeight)); } override public function createShapes():Array{ return (null); } private function onTouch(a_touchEvent:TouchEvent):void{ var engine:Engine; var waveBounds:Rectangle; if (m_activated){ return; }; if (a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false)){ m_activated = true; engine = entity.getEngine(); engine.dispatchEvent(new ChangeViewTargetEvent(this.entity.id)); waveBounds = calculateWaveBounds(); createWorldBoundaries(waveBounds); engine.createEntity(new EntitySpawnInfo("left_wave_boundary", "left_wave_boundary", (waveBounds.x - (BOUNDARY_THICKNESS / 2)), (waveBounds.y + (waveBounds.height / 2)))); engine.createEntity(new EntitySpawnInfo("right_wave_boundary", "right_wave_boundary", (waveBounds.right + (BOUNDARY_THICKNESS / 2)), (waveBounds.y + (waveBounds.height / 2)))); engine.createEntity(new EntitySpawnInfo("bottom_wave_boundary", "bottom_wave_boundary", (waveBounds.x + (waveBounds.width / 2)), (waveBounds.bottom + (BOUNDARY_THICKNESS / 2)))); engine.createEntity(new EntitySpawnInfo("top_wave_boundary", "top_wave_boundary", (waveBounds.x + (waveBounds.width / 2)), (waveBounds.top - (BOUNDARY_THICKNESS / 2)))); }; } private function cleanup():void{ var engine:Engine = entity.getEngine(); engine.dispatchEvent(new ChangeViewTargetEvent("")); engine.destroyEntity("left_wave_boundary"); engine.destroyEntity("right_wave_boundary"); engine.destroyEntity("top_wave_boundary"); engine.destroyEntity("bottom_wave_boundary"); engine.removeEntityType("left_wave_boundary"); engine.removeEntityType("right_wave_boundary"); engine.removeEntityType("top_wave_boundary"); engine.removeEntityType("bottom_wave_boundary"); } private function createWorldBoundaries(a_waveBounds:Rectangle):void{ var entityDef:EntityTypeDefinition; var polyDef:PolygonDef; var bodyDef:b2BodyDef; var boundaryGroupFilter:int; var categoryBits:int = Constants.COMBAT_WAVE_BOUNDARY_COLLISION_CATEGORY; var engine:Engine = entity.getEngine(); engine.removeEntityType("left_wave_boundary"); engine.removeEntityType("right_wave_boundary"); engine.removeEntityType("top_wave_boundary"); engine.removeEntityType("bottom_wave_boundary"); var drawBoundaries:Boolean; entityDef = new EntityTypeDefinition(); entityDef.type = "left_wave_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((BOUNDARY_THICKNESS / 2), (a_waveBounds.height / 2)); polyDef.groupFilter = boundaryGroupFilter; polyDef.categoryBits = categoryBits; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "right_wave_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((BOUNDARY_THICKNESS / 2), (a_waveBounds.height / 2)); polyDef.groupFilter = boundaryGroupFilter; polyDef.categoryBits = categoryBits; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "bottom_wave_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((a_waveBounds.width / 2), (BOUNDARY_THICKNESS / 2)); polyDef.groupFilter = boundaryGroupFilter; polyDef.categoryBits = categoryBits; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "top_wave_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((a_waveBounds.width / 2), (BOUNDARY_THICKNESS / 2)); polyDef.groupFilter = boundaryGroupFilter; polyDef.categoryBits = categoryBits; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; engine.addEntityType(entityDef); } override public function dispose():void{ } private function spawnNextWave():void{ var player:Entity; var musicClass:Class; var spawnInfo:SpawnInfo; trace(("Spawning for wave :" + m_waveIndex)); var engine:Engine = entity.getEngine(); if (m_waveIndex >= m_waves.length){ cleanup(); if (winOnDefeat){ player = entity.getEngine().lookupEntity("my_player"); player.properties.setBoolean("touchedExit", true); } else { musicClass = (getDefinitionByName("MUSIC_BOSS") as Class); //unresolved jump var _slot1 = e; musicClass = null; if (((!((musicClass == null))) && (Constants.MUSIC_ENABLED))){ SoundSystem.instance.createLoop("background", new MUSIC_IN_GAME()); }; engine.renderer.view.clearTemporaryBounds(); engine.destroyEntity(entity.id); }; return; }; m_activeEntityIDs.splice(0); m_delayedSpawns.splice(0); var wave:Wave = m_waves[m_waveIndex]; var spawns:Array = wave.spawns; var s:int; while (s < spawns.length) { spawnInfo = spawns[s]; if (spawnInfo.delay <= 0){ spawn(spawnInfo); } else { queueSpawn(spawnInfo); }; s = (s + 1); }; m_waveIndex++; } override public function tick(a_deltaTime:Number):void{ var waveBounds:Rectangle; var musicClass:Class; var entityID:String; var waveEntity:Entity; var timeAlive:Number; var boundaryIgnoreInterval:Number; var s:b2Shape; var filterData:b2FilterData; var delayedSpawn:DelayedActiveSpawn; var a_deltaTime = a_deltaTime; if (!m_activated){ return; }; var engine:Engine = entity.getEngine(); if (!m_started){ if (!engine.renderer.view.isAtTarget()){ return; }; waveBounds = calculateWaveBounds(); engine.renderer.view.setTemporaryBounds(waveBounds.x, waveBounds.y, waveBounds.width, waveBounds.height); m_started = true; musicClass = (getDefinitionByName("MUSIC_BOSS") as Class); //unresolved jump var _slot1 = e; musicClass = null; if (((!((musicClass == null))) && (Constants.MUSIC_ENABLED))){ SoundSystem.instance.destroyLoop("background"); SoundSystem.instance.createLoop("background", new (musicClass)); }; }; if (m_delayBetweenWavesTimer >= 0){ m_delayBetweenWavesTimer = (m_delayBetweenWavesTimer - a_deltaTime); if (m_delayBetweenWavesTimer < 0){ spawnNextWave(); }; return; }; var i:int = (m_activeEntityIDs.length - 1); while (i >= 0) { entityID = m_activeEntityIDs[i]; waveEntity = engine.lookupEntity(entityID); if (waveEntity == null){ m_activeEntityIDs.splice(i, 1); } else { timeAlive = 0; if (m_aliveTime[entityID] != null){ timeAlive = m_aliveTime[entityID]; }; timeAlive = (timeAlive + a_deltaTime); m_aliveTime[entityID] = timeAlive; boundaryIgnoreInterval = 1000; if ((((timeAlive >= boundaryIgnoreInterval)) && (((timeAlive - a_deltaTime) < boundaryIgnoreInterval)))){ s = waveEntity.body.GetShapeList(); while (s) { filterData = s.GetFilterData(); filterData.maskBits = (filterData.maskBits | Constants.COMBAT_WAVE_BOUNDARY_COLLISION_CATEGORY); s.SetFilterData(filterData); waveEntity.getEngine().getDynamics().refilter(s); s = s.GetNext(); }; }; }; i = (i - 1); }; var d:int = (m_delayedSpawns.length - 1); while (d >= 0) { delayedSpawn = m_delayedSpawns[d]; delayedSpawn.tick(a_deltaTime); if (delayedSpawn.hasDelayPassed()){ spawn(delayedSpawn.spawnInfo); m_delayedSpawns.splice(d, 1); }; d = (d - 1); }; if ((((m_activeEntityIDs.length == 0)) && ((m_delayedSpawns.length == 0)))){ m_delayBetweenWavesTimer = delayBetweenWaves; }; } private function queueSpawn(a_spawnInfo:SpawnInfo):void{ var delayedSpawn:DelayedActiveSpawn = new DelayedActiveSpawn(a_spawnInfo); m_delayedSpawns.push(delayedSpawn); } private function spawn(a_spawnInfo:SpawnInfo):void{ var positionX:Number; var positionY:Number = a_spawnInfo.positionY; var side:int = a_spawnInfo.side; var type:String = a_spawnInfo.type; var vx:Number = a_spawnInfo.vx; var vy:Number = a_spawnInfo.vy; var delay:Number = a_spawnInfo.delay; var flipped:Boolean; if (side == LEFT_WALL){ positionX = ((-(waveBoxWidth) / 2) + 5); } else { positionX = ((waveBoxWidth / 2) - 5); flipped = true; }; var engine:Engine = entity.getEngine(); positionX = (positionX + this.entity.getPosition().x); positionY = (positionY + (this.entity.getPosition().y + spawnOffsetY)); var id:String = ("w" + Math.random()); m_activeEntityIDs.push(id); var spawnedEntity:Entity = engine.createEntity(new EntitySpawnInfo(type, id, positionX, positionY, vx, vy, 0, 1, null, PruneType.IMMUNE)); spawnedEntity.flip = flipped; } } }//package game.behaviors class Wave { public var spawns:Array; private function Wave(){ spawns = []; super(); } public function addSpawn(a_positionY:Number, a_type:String, a_side:int, a_vx:Number, a_vy:Number, a_delay:Number):void{ spawns.push(new SpawnInfo(a_positionY, a_type, a_side, a_vx, a_vy, a_delay)); } public function toString():String{ return ((("<Wave:" + spawns) + ">")); } } class DelayedActiveSpawn { public var timer:Number; public var spawnInfo:SpawnInfo; private function DelayedActiveSpawn(a_spawnInfo:SpawnInfo){ super(); timer = 0; spawnInfo = a_spawnInfo; } public function hasDelayPassed():Boolean{ return ((timer > spawnInfo.delay)); } public function toString():String{ return ((("<DelayedActiveSpawn:" + spawnInfo) + ">")); } public function tick(a_interval:Number):void{ timer = (timer + a_interval); } } class SpawnInfo { public var vx:Number; public var vy:Number; public var delay:Number; public var positionY:Number; public var side:int; public var type:String; private function SpawnInfo(a_positionY:Number, a_type:String, a_side:int, a_vx:Number, a_vy:Number, a_delay:Number){ super(); positionY = a_positionY; type = a_type; side = a_side; vx = a_vx; vy = a_vy; delay = a_delay; } public function toString():String{ return ((((((("<SpawnInfo:" + type) + ",") + side) + ",") + positionY) + ">")); } }
Section 185
//CrouchBehavior (game.behaviors.CrouchBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; public class CrouchBehavior extends Behavior { private var m_upperBodyShape:b2Shape; private var m_animationPlayer:AnimationPlayer;// = null public static const CROUCH_HEIGHT:Number = 14; public function CrouchBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } override public function tick(a_interval:Number):void{ var upperBody:PolygonDef; var shapeDef:b2ShapeDef; if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (m_animationPlayer.currentAnimationID.indexOf("crouch") >= 0){ if (m_upperBodyShape != null){ entity.body.DestroyShape(m_upperBodyShape); m_upperBodyShape = null; }; } else { if (m_upperBodyShape == null){ upperBody = new PolygonDef(); upperBody.friction = 0.01; upperBody.restitution = 0; upperBody.density = 1; upperBody.makeCenteredBox((19 / 2), CROUCH_HEIGHT, 0, (-0.5 * CROUCH_HEIGHT)); shapeDef = upperBody.createBox2DShape(Dynamics.SCALE); m_upperBodyShape = entity.body.CreateShape(shapeDef); }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 186
//CrumblingBlockBehavior (game.behaviors.CrumblingBlockBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; public class CrumblingBlockBehavior extends Behavior { private var m_shape:b2Shape; private var hasActivated:Boolean;// = false private var m_timer:Number;// = 0 private var m_isBeingTouched:Boolean;// = false private static const RECHARGE_TIMER:Number = 4000; public function CrumblingBlockBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var entityPlayerIsStandingOnID:String; var entityPlayerIsStandingOn:Entity; if (a_touchEvent.theirEntity == null){ return; }; if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity.id != "my_player"){ return; }; m_isBeingTouched = true; if (a_touchEvent.myShape != m_shape){ return; }; if (!a_touchEvent.theirEntity.properties.getBoolean("standingOnSomething", false)){ entityPlayerIsStandingOnID = a_touchEvent.theirEntity.properties.getString("standingOnID", ""); entityPlayerIsStandingOn = entity.getEngine().lookupEntity(entityPlayerIsStandingOnID); if (entityPlayerIsStandingOn != entity){ return; }; }; activate(); } private function createCollisionShape():PolygonDef{ var polyDef:PolygonDef; polyDef = new PolygonDef(); polyDef.makeCenteredBox((64 / 2), (5 / 2), 0, 24); polyDef.density = 2.5; polyDef.friction = 1; polyDef.userData = this; return (polyDef); } public function activate():void{ if (hasActivated){ return; }; hasActivated = true; var ginger:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; if (!ginger.hasEventListener(AnimationEvent.CHANGE)){ ginger.addEventListener(AnimationEvent.CHANGE, onAnimationChange, false, 0, true); }; ginger.play("disintegrate"); m_timer = RECHARGE_TIMER; } private function onAnimationChange(a_animationEvent:AnimationEvent):void{ var animationID:String = a_animationEvent.animationID; if ((((animationID == "regrow")) && (!(a_animationEvent.begin)))){ hasActivated = false; }; if (animationID != "disintegrate"){ return; }; if (a_animationEvent.begin){ return; }; entity.body.DestroyShape(m_shape); var ginger:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; ginger.play("idle_disintegrated"); } override public function tick(a_deltaTime:Number):void{ var ginger:AnimationPlayer; var polyDef:PolygonDef; var shapeDef:b2ShapeDef; if (m_timer < 0){ return; }; m_timer = (m_timer - a_deltaTime); if (m_timer <= 0){ if (!m_isBeingTouched){ ginger = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; ginger.play("regrow"); polyDef = createCollisionShape(); shapeDef = polyDef.createBox2DShape(Dynamics.SCALE); m_shape = entity.body.CreateShape(shapeDef); } else { m_timer = 0; }; }; m_isBeingTouched = false; } override public function dispose():void{ } } }//package game.behaviors
Section 187
//DrillBoxBehavior (game.behaviors.DrillBoxBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; public class DrillBoxBehavior extends Behavior { private var spawnFrequency:Number; private var maxAliveCount:int; private var m_spawnedEntities:Array; private var m_activated:Boolean;// = false private var spawnType:String; private var m_spawnTimer:Number; private var m_playedLeaveSound:Boolean;// = false private var m_state:Function; public function DrillBoxBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ m_state = tickNone; m_spawnedEntities = []; spawnFrequency = 4000; spawnType = Constants.ENTITY_TYPE_SWORD_NINJA; maxAliveCount = 3; super(a_entity, a_name, a_data); if (a_entity.properties.exists("spawnType")){ spawnType = a_entity.properties.getString("spawnType", Constants.ENTITY_TYPE_SWORD_NINJA); }; if (a_entity.properties.exists("maxAliveCount")){ maxAliveCount = a_entity.properties.getInt("maxAliveCount", 3); }; if (a_entity.properties.exists("spawnFrequency")){ spawnFrequency = a_entity.properties.getNumber("spawnFrequency", 4000); }; this.entity.properties.setBoolean("isInvincible", true); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (userData == "sensor"){ if (m_activated){ return; }; m_activated = true; m_state = tickInit; }; } private function tickActive(a_deltaTime:Number):void{ var id:String; var spawnedID:String; if (this.entity.properties.getInt("lives", 1) <= 0){ if (!m_playedLeaveSound){ m_playedLeaveSound = true; SoundSystem.instance.playSound(new DrillBox()); }; return; }; if (m_spawnedEntities.length < maxAliveCount){ m_spawnTimer = (m_spawnTimer - a_deltaTime); if (m_spawnTimer <= 0){ m_spawnTimer = spawnFrequency; id = ("s" + Math.random()); m_spawnedEntities.push(id); entity.getEngine().createEntity(new EntitySpawnInfo(spawnType, id, entity.getPosition().x, entity.getPosition().y)); }; }; var i:int = (m_spawnedEntities.length - 1); while (i >= 0) { spawnedID = m_spawnedEntities[i]; if (entity.getEngine().lookupEntity(spawnedID) == null){ m_spawnedEntities.splice(i); }; i--; }; } override public function tick(a_deltaTime:Number):void{ m_state(a_deltaTime); } private function tickNone(a_deltaTime:Number):void{ } override public function createShapes():Array{ var attackSensor:PolygonDef = new PolygonDef(); attackSensor.makeCenteredBox(150, 180, 0, 15); attackSensor.isSensor = true; attackSensor.maskBits = Constants.PLAYER_COLLISION_CATEGORY; attackSensor.userData = "sensor"; return ([attackSensor]); } private function tickArriving(a_deltaTime:Number):void{ var animationPlayer:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; if (animationPlayer.currentAnimationID == "arrive"){ return; }; if (animationPlayer.currentAnimationID == "idle"){ this.entity.properties.setBoolean("isInvincible", false); m_spawnTimer = 0; m_state = tickActive; }; } private function tickInit(a_deltaTime:Number):void{ var animationPlayer:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; animationPlayer.play("arrive"); animationPlayer.defaultAnimationID = "idle"; m_state = tickArriving; SoundSystem.instance.playSound(new DrillBox()); } override public function dispose():void{ } } }//package game.behaviors
Section 188
//FlinchBehavior (game.behaviors.FlinchBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.audio.*; import flash.media.*; import game.events.*; import com.urbansquall.prophet.utils.*; import game.*; public class FlinchBehavior extends Behavior { public var tweenAlphaOnDeath:Boolean;// = true private var m_flinchGraceTime:int; private var m_isActive:Boolean; private var m_isDying:Boolean; private var m_animator:AnimationPlayer; public var soundProfile:String;// = "" private static const FLINCH_GRACE_TIME:int = 400; public function FlinchBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_isActive = false; m_flinchGraceTime = 0; m_isDying = false; } private function die():void{ var player:Entity; var spawnType:String; var props:KeyValueMap; if (m_isDying){ return; }; m_isDying = true; m_isActive = true; var givesPlayerABoostOfOoze:Boolean; if (givesPlayerABoostOfOoze){ player = entity.getEngine().lookupEntity("my_player"); if (player != null){ if (Math.random() < 0.1){ spawnType = Constants.ENTITY_TYPE_PIZZA; } else { spawnType = Constants.ENTITY_TYPE_OOZE_CAN; }; props = new KeyValueMap(); props.setBoolean("expireEnabled", true); entity.getEngine().createEntity(new EntitySpawnInfo(spawnType, "", entity.getPosition().x, entity.getPosition().y, 0, 0, 0, 1, props)); }; }; m_animator.addEventListener(AnimationEvent.CHANGE, onDeathChange); m_animator.defaultAnimationID = "death"; m_animator.play("death"); var deathSound:Sound = getDeathSound(); if (deathSound != null){ SoundSystem.instance.playSound(deathSound); }; entity.getEngine().dispatchEvent(new ChangeStatisticEvent(Statistics.ENEMIES_KILLED, 1)); if (tweenAlphaOnDeath){ Tweener.addTween(m_animator, {alpha:0.1, time:2}); }; knockback(); } private function getHitSound():Sound{ var hitOptions:Array; var randomOption:Sound; if (soundProfile == "human"){ hitOptions = [SoundCache.footSoldierHit1, SoundCache.footSoldierHit2, SoundCache.footSoldierHit3]; } else { if (soundProfile == "robot"){ return (SoundCache.robotHit1); }; trace((("No sound profile for [" + soundProfile) + "]")); return (null); }; randomOption = hitOptions[Math.floor((hitOptions.length * Math.random()))]; return (randomOption); } private function onDeathChange(a_event:AnimationEvent):void{ if ((((a_event.animationID == "death")) && (!(a_event.begin)))){ m_animator.removeEventListener(AnimationEvent.CHANGE, onDeathChange); this.entity.getEngine().destroyEntity(this.entity.id); }; } private function onFlinchChange(a_event:AnimationEvent):void{ if ((((a_event.animationID == "flinch")) && (!(a_event.begin)))){ m_animator.removeEventListener(AnimationEvent.CHANGE, onFlinchChange); m_flinchGraceTime = FLINCH_GRACE_TIME; m_animator.play("idle"); }; } private function flinch():void{ m_isActive = true; m_flinchGraceTime = 0; this.entity.setVelocity(0, 0); this.entity.properties.setBoolean("isFlinching", false); if (m_animator.hasEventListener(AnimationEvent.CHANGE)){ m_animator.removeEventListener(AnimationEvent.CHANGE, onFlinchChange); }; m_animator.addEventListener(AnimationEvent.CHANGE, onFlinchChange); if (this.entity.properties.getBoolean("hasKnockback", false)){ knockback(); }; this.entity.properties.setInt("flinchingDir", 0); var flinchSound:Sound = getHitSound(); if (flinchSound != null){ SoundSystem.instance.playSound(flinchSound); }; m_animator.play("flinch"); //unresolved jump var _slot1 = e; trace(("No flinch for " + this.entity)); } public function get isActive():Boolean{ return (m_isActive); } private function getDeathSound():Sound{ var hitOptions:Array; var randomOption:Class; if (soundProfile == "human"){ hitOptions = [FootSoldierDie, FootSoldierDie2]; } else { if (soundProfile == "robot"){ return (new MachineDie1()); }; trace((("No sound profile for [" + soundProfile) + "]")); return (null); }; randomOption = hitOptions[Math.floor((hitOptions.length * Math.random()))]; return (new (randomOption)); } private function knockback():void{ var xKnock:Number = 170; if (this.entity.properties.getInt("flinchingDir", 1) < 0){ xKnock = -(xKnock); }; this.entity.setVelocity(xKnock, -110); } override public function tick(a_deltaTime:Number):void{ if (m_animator == null){ m_animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (this.entity.properties.getBoolean("isInvincible", false)){ return; }; if (this.entity.properties.getBoolean("isFlinching", false)){ flinch(); } else { if (this.entity.properties.getInt("lives", 1) <= 0){ die(); } else { if (m_flinchGraceTime > 0){ m_flinchGraceTime = (m_flinchGraceTime - a_deltaTime); if (m_flinchGraceTime <= 0){ m_isActive = false; }; }; }; }; } public function get isFlinchGrace():Boolean{ return ((m_flinchGraceTime > 0)); } override public function dispose():void{ } } }//package game.behaviors
Section 189
//GraphicsFaceRightBehavior (game.behaviors.GraphicsFaceRightBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class GraphicsFaceRightBehavior extends Behavior { public function GraphicsFaceRightBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } override public function tick(a_deltaTime:Number):void{ if (entity.getVelocity().x < 0){ entity.flip = true; } else { entity.flip = false; }; } override public function dispose():void{ } } }//package game.behaviors
Section 190
//HealthItemBehavior (game.behaviors.HealthItemBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; import game.*; public class HealthItemBehavior extends Behavior { public var healAmount:int;// = 2 private var eaten:Boolean;// = false private var m_healthSound:Sound;// = null public function HealthItemBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_healthSound = new PizzaPowerUp(); healAmount = a_data.getInt("healAmount", healAmount); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (a_touchEvent.theirShape.IsSensor()){ return; }; if (eaten){ return; }; var theirEntity:Entity = a_touchEvent.theirEntity; if (theirEntity.properties.getBoolean("isTurtle", false)){ Gameplay.healPlayer(theirEntity, healAmount); eaten = true; SoundSystem.instance.playSound(m_healthSound, 2); entity.getEngine().destroyEntity(entity.id); }; } override public function dispose():void{ } } }//package game.behaviors
Section 191
//HunBehavior (game.behaviors.HunBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; import flash.utils.*; import Box2D.Common.Math.*; import game.*; public class HunBehavior extends Behavior { private var m_player:Entity; private var m_chargeStartPosition:Point; private var m_stepSound:Sound; private var m_henchman1ID:String; private var m_henchman2ID:String; private var m_chargeChances:int; private var m_chargeDirection:int;// = -1 private var m_hitWallSound:Sound; private var m_cooldownTime:int; private var m_stateFunction:Function; private var m_origin:Point; private var m_animationPlayer:AnimationPlayer;// = null private static const PUNCH_DAMAGE:int = 5; private static const COOLDOWN_TIME:int = 4000; private static const SENSOR_WIDTH:int = 80; private static const CHARGE_CHANCES:int = 3; private static const CHARGE_DISTANCE:int = 150; private static const CHARGE_SPEED:int = 210; private static const CHARGE_START_DISTANCE:int = 80; public function HunBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_stateFunction = tickStart; m_stepSound = new HunStep(); m_hitWallSound = new HunHitWall(); } private function isRunningIntoWall():Boolean{ return (((this.entity.properties.getBoolean("touchingWall", false)) && ((((((m_chargeDirection > 0)) && (this.entity.properties.getBoolean("rightWall", true)))) || ((((m_chargeDirection < 0)) && (this.entity.properties.getBoolean("leftWall", true)))))))); } private function spawnFooties():void{ if (hasHenchmen()){ return; }; var playerPosition:Point = m_player.getPosition(); m_henchman1ID = ("h" + Math.random()); m_henchman2ID = ("h" + Math.random()); entity.getEngine().createEntity(new EntitySpawnInfo(Constants.ENTITY_TYPE_SWORD_NINJA, m_henchman1ID, 540, (playerPosition.y - 320))); entity.getEngine().createEntity(new EntitySpawnInfo(Constants.ENTITY_TYPE_SWORD_NINJA, m_henchman2ID, 1160, (playerPosition.y - 320))); } private function tickWaitForFootiesToDie(a_deltaTime:Number):void{ var xDist:Number = (m_player.getPosition().x - this.entity.getPosition().x); if (xDist < 0){ entity.flip = true; } else { entity.flip = false; }; if (!hasHenchmen()){ m_stateFunction = tickRun; m_chargeChances = CHARGE_CHANCES; entity.properties.setBoolean("isInvincible", true); } else { if (m_animationPlayer.currentAnimationID != "punch"){ if (Math.abs(xDist) <= SENSOR_WIDTH){ m_animationPlayer.play("punch"); }; }; }; } private function tickStart(a_deltaTime:Number):void{ if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animationPlayer.addEventListener(FrameEvent.CHANGE, handleFrameChanged, false, 0, true); m_animationPlayer.addEventListener(AnimationEvent.CHANGE, handleAnimationChanged, false, 0, true); }; if (m_player == null){ m_player = entity.getEngine().lookupEntity("my_player"); }; SoundSystem.instance.playSound(new HunHuff()); m_origin = this.entity.getPosition(); m_stateFunction = callReinforcements; } private function handleFrameChanged(a_frameEvent:FrameEvent):void{ var attackOffsetX:Number; var attackOffsetY:Number; var attackWidth:Number; var attackHeight:Number; var startX:Number; var startY:Number; var boxedEntities:Array; var b:int; if (m_stateFunction == callReinforcements){ if ((((a_frameEvent.animationID == "pump")) && ((a_frameEvent.frameID == "end")))){ spawnFooties(); m_stateFunction = tickWaitForFootiesToDie; }; return; }; if (a_frameEvent.frameID.indexOf("step") >= 0){ if (m_stateFunction == tickRun){ this.entity.getEngine().renderer.view.shakeView(100, 6); }; SoundSystem.instance.playSound(m_stepSound); }; if (m_animationPlayer.currentFrameID == "punch_1"){ attackOffsetX = 10; attackOffsetY = -57; attackWidth = 60; attackHeight = 110; startX = (this.entity.getPosition().x + attackOffsetX); startY = (this.entity.getPosition().y + attackOffsetY); if (this.entity.flipped){ startX = ((this.entity.getPosition().x - attackOffsetX) - attackWidth); }; boxedEntities = entity.getEngine().queryBox(startX, startY, attackWidth, attackHeight); b = 0; while (b < boxedEntities.length) { AttackManager.enemyAttack(this.entity, boxedEntities[b], PUNCH_DAMAGE); b++; }; SoundSystem.instance.playSound(new StrongPunchAttack1()); }; } private function onWallStunChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animationPlayer.removeEventListener(AnimationEvent.CHANGE, onWallStunChange); m_stateFunction = tickStunned; }; } private function handleAnimationChanged(a_event:AnimationEvent):void{ var s:b2Shape; var henchman:Entity; if (((a_event.begin) && ((a_event.animationID == "death")))){ s = entity.body.GetShapeList(); while (s) { entity.body.DestroyShape(s); s = s.GetNext(); }; entity.body.SetStatic(); SoundSystem.instance.playSound(new HunDie()); henchman = entity.getEngine().lookupEntity(m_henchman1ID); if (henchman != null){ henchman.properties.setInt("lives", 0); }; henchman = entity.getEngine().lookupEntity(m_henchman2ID); if (henchman != null){ henchman.properties.setInt("lives", 0); }; }; if (((!(a_event.begin)) && ((a_event.animationID == "death")))){ m_player.properties.setBoolean("touchedExit", true); }; if (a_event.animationID == "charge"){ if (a_event.begin){ SoundSystem.instance.createLoop("huncharge", new WallSlide(), 1, true, true); } else { SoundSystem.instance.destroyLoop("huncharge"); }; }; } private function hasHenchmen():Boolean{ var henchman:Entity = entity.getEngine().lookupEntity(m_henchman1ID); if (henchman != null){ return (true); }; henchman = entity.getEngine().lookupEntity(m_henchman2ID); if (henchman != null){ return (true); }; return (false); } override public function tick(a_deltaTime:Number):void{ if (entity.properties.getInt("lives", 1) <= 0){ return; }; if (m_stateFunction != tickCharge){ if (SoundSystem.instance.isPlaying("huncharge")){ SoundSystem.instance.destroyLoop("huncharge"); }; }; m_stateFunction(a_deltaTime); } override public function dispose():void{ SoundSystem.instance.destroyLoop("huncharge"); } private function tickHitWall(a_deltaTime:Number):void{ if (m_animationPlayer.currentAnimationID == "wallstun"){ return; }; this.entity.getEngine().renderer.view.shakeView(250, 10); m_animationPlayer.play("wallstun"); m_animationPlayer.addEventListener(AnimationEvent.CHANGE, onWallStunChange); m_cooldownTime = COOLDOWN_TIME; } private function returnToOrigin(a_deltaTime:Number):void{ entity.properties.setBoolean("isInvincible", true); if (m_animationPlayer.currentAnimationID != "run"){ m_animationPlayer.play("run"); }; if (Math.abs((this.entity.getPosition().x - m_origin.x)) < 10){ SoundSystem.instance.playSound(new HunHuff()); m_stateFunction = callReinforcements; return; }; m_chargeDirection = 1; if (this.entity.getPosition().x > m_origin.x){ m_chargeDirection = -1; }; var velocity:Number = (CHARGE_SPEED * m_chargeDirection); if (velocity < 0){ entity.flip = true; } else { entity.flip = false; }; entity.setVelocity(velocity, entity.getVelocity().y); } private function callReinforcements(a_deltaTime:Number):void{ entity.properties.setBoolean("isInvincible", false); entity.setVelocity(0, 0); if (m_player.getPosition().x < entity.getPosition().x){ entity.flip = true; } else { entity.flip = false; }; if (m_animationPlayer.currentAnimationID != "pump"){ m_animationPlayer.play("pump"); }; } private function tickCharge(a_deltaTime:Number):void{ entity.properties.setBoolean("isInvincible", false); if (m_animationPlayer.currentAnimationID != "charge"){ m_animationPlayer.play("charge"); m_chargeChances = (m_chargeChances - 1); }; if (Math.abs((this.entity.getPosition().x - m_chargeStartPosition.x)) >= CHARGE_DISTANCE){ SoundSystem.instance.destroyLoop("huncharge"); if (m_chargeChances <= 0){ SoundSystem.instance.playSound(new HunHuff()); m_stateFunction = callReinforcements; } else { m_stateFunction = tickRun; }; return; }; if (isRunningIntoWall()){ SoundSystem.instance.playSound(m_hitWallSound); m_stateFunction = tickHitWall; this.entity.setVelocity(0, this.entity.getVelocity().y); return; }; var velocity:Number = (CHARGE_SPEED * m_chargeDirection); if (velocity < 0){ entity.flip = true; } else { entity.flip = false; }; entity.setVelocity(velocity, entity.getVelocity().y); } private function tickStunned(a_deltaTime:Number):void{ if (((((!((m_animationPlayer.currentAnimationID == "stunned"))) && (!((m_animationPlayer.currentAnimationID == "flinch"))))) && (!((m_animationPlayer.currentAnimationID == "death"))))){ m_animationPlayer.play("stunned"); }; m_cooldownTime = (m_cooldownTime - a_deltaTime); if (m_cooldownTime <= 0){ m_stateFunction = returnToOrigin; }; } private function tickRun(a_deltaTime:Number):void{ if (m_animationPlayer.currentAnimationID != "run"){ m_animationPlayer.play("run"); }; if (Math.abs((m_player.getPosition().x - this.entity.getPosition().x)) < CHARGE_START_DISTANCE){ m_chargeStartPosition = this.entity.getPosition(); m_stateFunction = tickCharge; return; }; if (isRunningIntoWall()){ m_chargeDirection = (m_chargeDirection * -1); }; var velocity:Number = (CHARGE_SPEED * m_chargeDirection); if (velocity < 0){ entity.flip = true; } else { entity.flip = false; }; entity.setVelocity(velocity, entity.getVelocity().y); } } }//package game.behaviors
Section 192
//JumpingNinjaBehavior (game.behaviors.JumpingNinjaBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.utils.*; public class JumpingNinjaBehavior extends Behavior { private var m_movingLeft:Boolean;// = true private var m_jumpSound:Sound;// = null private var m_lastX:int;// = 0 private var m_stuckCounter:int;// = 0 private var m_timer:Number;// = 0 private var m_stunTimer:Number;// = 0 private var m_animationPlayer:AnimationPlayer;// = null private var m_activated:Boolean;// = false private static const X_SPEED:int = 100; private static const TIMER_COOLDOWN:Number = 500; public function JumpingNinjaBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_jumpSound = new JumpingNinjaJump(); } override public function tick(a_deltaTime:Number):void{ var player:Entity; var playerX:Number; var myX:Number; if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animationPlayer.addEventListener(AnimationEvent.CHANGE, animationChange, false, 0, true); m_animationPlayer.addEventListener(FrameEvent.CHANGE, frameChange, false, 0, true); }; if (!m_activated){ testForActivation(); return; }; if ((this.entity.lookupBehavior("flinch") as FlinchBehavior).isActive){ m_stunTimer = 250; return; }; m_stunTimer = (m_stunTimer - a_deltaTime); if (m_stunTimer >= 0){ if (m_animationPlayer.currentAnimationID != "idle"){ m_animationPlayer.play("idle"); }; return; }; m_timer = (m_timer - a_deltaTime); if (m_timer <= 0){ trigger(); } else { player = entity.getEngine().lookupEntity("my_player"); playerX = 0; if (player != null){ playerX = player.getPosition().x; }; myX = entity.getPosition().x; if (Math.abs((playerX - myX)) < 5){ } else { if ((((playerX > myX)) && (entity.properties.getBoolean("standingOnSomething", false)))){ entity.flip = false; entity.setVelocity(X_SPEED, entity.getVelocity().y); } else { if (entity.properties.getBoolean("standingOnSomething", false)){ entity.flip = true; entity.setVelocity(-(X_SPEED), entity.getVelocity().y); }; }; }; if (entity.properties.getBoolean("standingOnSomething", false)){ if (((!((m_animationPlayer.currentAnimationID == "walk"))) && (!((m_animationPlayer.currentAnimationID == "jump"))))){ if (Math.abs(entity.getVelocity().x) < 0.001){ m_animationPlayer.play("idle"); } else { m_animationPlayer.play("walk"); }; }; }; }; } private function animationChange(a_event:AnimationEvent):void{ if (((!(a_event.begin)) && ((((a_event.animationID == "jump")) || ((a_event.animationID == "apex")))))){ if (entity.getVelocity().y < 0){ m_animationPlayer.play("apex"); } else { m_animationPlayer.play("fall"); }; }; } override public function dispose():void{ } private function trigger():void{ var player:Entity; var playerX:Number; var myX:Number; var jumpDirection:int; m_timer = TIMER_COOLDOWN; if (entity.properties.getBoolean("standingOnSomething", false)){ player = entity.getEngine().lookupEntity("my_player"); playerX = 0; if (player != null){ playerX = player.getPosition().x; }; myX = entity.getPosition().x; jumpDirection = -(X_SPEED); if (playerX > myX){ jumpDirection = -(jumpDirection); }; entity.setVelocity(jumpDirection, -300); m_animationPlayer.play("jump"); SoundSystem.instance.playSound(m_jumpSound); }; } private function testForActivation():void{ var viewX:Number = entity.getEngine().renderer.view.viewX; var myX:Number = entity.getPosition().x; var edge:Number = 30; if (myX < viewX){ edge = (edge * -1); }; var separation:Number = ((myX - edge) - viewX); if (Math.abs(separation) < (Constants.RENDER_WIDTH / 2)){ m_activated = true; }; } private function frameChange(a_event:AnimationEvent):void{ } } }//package game.behaviors
Section 193
//KnockbackOnTouchBehavior (game.behaviors.KnockbackOnTouchBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; import flash.utils.*; import game.*; public class KnockbackOnTouchBehavior extends Behavior { public var attackDamage:int;// = 2 public var soundToPlay:String;// = "" public function KnockbackOnTouchBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var soundClass:Class; var a_touchEvent = a_touchEvent; if (this.entity.properties.getInt("lives", 1) <= 0){ return; }; var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (a_touchEvent.myShape.IsSensor()){ return; }; if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity.properties.getBoolean("isInvincible", false)){ return; }; if (((!((soundToPlay == ""))) && (a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false)))){ soundClass = (getDefinitionByName(soundToPlay) as Class); if (soundClass != null){ SoundSystem.instance.playSound(new (soundClass)); }; //unresolved jump var _slot1 = e; trace((("No knockback sound matching [" + soundToPlay) + "]")); }; AttackManager.enemyAttack(this.entity, a_touchEvent.theirEntity, attackDamage); } override public function dispose():void{ } } }//package game.behaviors
Section 194
//LaserBehavior (game.behaviors.LaserBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class LaserBehavior extends Behavior { public var speed:Number;// = 60 private var leftHolder:Object; private var rightHolder:Object; public var verticalOffset:Number;// = 0 public var sensorRadius:Number;// = 3 private var fireTimer:int; public var movingLeft:Boolean;// = true private var m_yPosition:Number; public var isDebugEnabled:Boolean;// = false public var sensorWidth:Number;// = 17 public var propagatesSpeed:Boolean;// = true public function LaserBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); fireTimer = 10; } override public function createShapes():Array{ return ([]); } override public function tick(a_deltaTime:Number):void{ fireTimer--; if (fireTimer < 1){ this.entity.getEngine().destroyEntity(this.entity.id); }; } override public function dispose():void{ } } }//package game.behaviors
Section 195
//LaserNinjaBehavior (game.behaviors.LaserNinjaBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.utils.*; public class LaserNinjaBehavior extends Behavior { private var m_animationPlayer:AnimationPlayer;// = null private var m_postFireStickTimer:Number;// = -1 public var speed:Number;// = 60 public var verticalOffset:Number;// = 0 public var sensorRadius:Number;// = 3 public var sensorWidth:Number;// = 17 public var movingLeft:Boolean;// = true private var m_yPosition:Number; public var propagatesSpeed:Boolean;// = false public var isDebugEnabled:Boolean;// = false private static const HORIZONTAL_SPEED:Number = 8; private static const POST_FIRE_STICK_TIME:Number = 3000; public function LaserNinjaBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_yPosition = a_entity.getSpawnInfo().y; } private function calculateVelocity():Number{ var velocity:Number = speed; return (velocity); } override public function dispose():void{ } private function animationChange(a_animationEvent:AnimationEvent):void{ var spawnInfo:EntitySpawnInfo; if (((a_animationEvent.begin) && ((a_animationEvent.animationID == "attack")))){ SoundSystem.instance.playSound(new ProlongingLaserBeam1()); } else { if (((!(a_animationEvent.begin)) && ((a_animationEvent.animationID == "attack")))){ spawnInfo = new EntitySpawnInfo(Constants.ENTITY_TYPE_LASER, "", (this.entity.getPosition().x + 4), (this.entity.getPosition().y + 210), 0, 6, 0, 1, null); entity.getEngine().createEntity(spawnInfo); m_postFireStickTimer = POST_FIRE_STICK_TIME; } else { if (((!(a_animationEvent.begin)) && ((a_animationEvent.animationID == "flinch")))){ if (m_postFireStickTimer > 1000){ m_postFireStickTimer = 1000; }; }; }; }; } override public function tick(a_deltaTime:Number):void{ if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animationPlayer.addEventListener(AnimationEvent.CHANGE, animationChange, false, 0, true); }; if (entity.properties.getInt("lives", 1) < 0){ return; }; m_postFireStickTimer = (m_postFireStickTimer - a_deltaTime); if ((((m_postFireStickTimer > 0)) && ((m_postFireStickTimer <= 2)))){ SoundSystem.instance.playSound(new ShortLaserChargeUp1()); }; if (m_postFireStickTimer > 0){ return; }; if (m_animationPlayer.currentAnimationID == "attack"){ return; }; var player:Entity = entity.getEngine().lookupEntity("my_player"); var directionX:Number = (player.getPosition().x - entity.getPosition().x); var velocity:Number = HORIZONTAL_SPEED; if (directionX < 0){ velocity = (velocity * -1); }; if (Math.abs(directionX) < 5){ velocity = 0; }; entity.setPosition((entity.getPosition().x + velocity), m_yPosition); if (velocity == 0){ m_animationPlayer.play("attack"); }; } } }//package game.behaviors
Section 196
//MovingSpecialAttackBehavior (game.behaviors.MovingSpecialAttackBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; import flash.utils.*; import game.*; public class MovingSpecialAttackBehavior extends Behavior { public var damageAmount:int;// = 310 public var damageType:String;// = "humans" private var m_touched:Dictionary; private var m_disabled:Boolean;// = false public var activeTime:int;// = 950 public function MovingSpecialAttackBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_touched = new Dictionary(false); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (m_disabled){ return; }; if (a_touchEvent.theirEntity == null){ return; }; if (a_touchEvent.theirEntity.id == "my_player"){ return; }; if (m_touched[a_touchEvent.theirEntity.id] != null){ return; }; if (!a_touchEvent.theirEntity.properties.getBoolean("isEnemy", false)){ return; }; m_touched[a_touchEvent.theirEntity.id] = a_touchEvent.theirEntity.id; var flinchDir = -1; var player:Entity = entity.getEngine().lookupEntity("my_player"); if (player.getPosition().x < a_touchEvent.theirEntity.getPosition().x){ flinchDir = 1; }; AttackManager.doTurtleAttack(a_touchEvent.theirEntity, damageAmount, damageType, flinchDir, true); } private function expire():void{ entity.getEngine().destroyEntity(entity.id); } override public function tick(a_interval:Number):void{ var tweenTime:Number; var g:int; var graphic:Graphic; if (m_disabled){ return; }; activeTime = (activeTime - a_interval); if (activeTime < 0){ m_disabled = true; tweenTime = 1; g = 0; while (g < entity.graphics.length) { graphic = entity.graphics[g]; if (g == (entity.graphics.length - 1)){ Tweener.addTween(graphic.display, {scaleY:0, time:tweenTime, onComplete:expire, onCompleteParams:[]}); } else { Tweener.addTween(graphic.display, {scaleY:0, time:tweenTime}); }; g++; }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 197
//OnTouchExitBehavior (game.behaviors.OnTouchExitBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class OnTouchExitBehavior extends Behavior { private var m_collected:Boolean;// = false public function OnTouchExitBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirEntity == null){ return; }; if (m_collected){ return; }; var player:Entity = a_touchEvent.theirEntity; if (player.id != "my_player"){ return; }; m_collected = true; player.properties.setBoolean("touchedExit", true); } override public function dispose():void{ } } }//package game.behaviors
Section 198
//PatrolBehavior (game.behaviors.PatrolBehavior) package game.behaviors { import flash.events.*; import shared.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; public class PatrolBehavior extends Behavior { private var m_curWalkSoundTimeOut:Number;// = 0 private var m_walkSound:Sound;// = null private var m_isFirstTime:Boolean;// = true private var lastX:Number; private var directionSwapTimeout:int; private var leftHolder:Object; private var leftFootDown:Boolean;// = true private var m_walkSoundPlaying:Boolean;// = false private var leftFootHolder:Object; public var entityWidth:int;// = 20 private var rightHolder:Object; public var verticalOffset:int;// = 7 private var rightFootDown:Boolean;// = true private var m_walkSoundTimeOut:Number;// = 500 public var entityHeight:int;// = 54 public var sensorRadius:int;// = 5 public var movingLeft:Boolean;// = true private var rightFootHolder:Object; public var isDebugEnabled:Boolean;// = false private var m_activated:Boolean;// = false public function PatrolBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); directionSwapTimeout = 5; if (a_data != null){ m_walkSound = (a_data.getObject("walkSound", null) as Sound); }; this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, checkPlatform); } private function onWalkSoundComplete(a_event:Event):void{ m_walkSoundPlaying = false; } private function moveLeft():void{ movingLeft = true; } private function moveRight():void{ movingLeft = false; } override public function createShapes():Array{ var circleDef:CircleGraphicDefinition; var graphic:Graphic; leftHolder = new Object(); rightHolder = new Object(); leftFootHolder = new Object(); rightFootHolder = new Object(); var leftSensor:CircleDef = new CircleDef(); leftSensor.localPosition.x = ((-(entityWidth) / 2) + (0.5 * sensorRadius)); leftSensor.localPosition.y = verticalOffset; leftSensor.radius = sensorRadius; leftSensor.isSensor = true; leftSensor.userData = leftHolder; var rightSensor:CircleDef = new CircleDef(); rightSensor.localPosition.x = ((entityWidth / 2) - (0.5 * sensorRadius)); rightSensor.localPosition.y = verticalOffset; rightSensor.radius = sensorRadius; rightSensor.isSensor = true; rightSensor.userData = rightHolder; var leftFootSensor:CircleDef = new CircleDef(); leftFootSensor.localPosition.x = ((-(entityWidth) / 2) + (0.5 * sensorRadius)); leftFootSensor.localPosition.y = (entityHeight + 5); leftFootSensor.radius = sensorRadius; leftFootSensor.isSensor = true; leftFootSensor.userData = leftFootHolder; var rightFootSensor:CircleDef = new CircleDef(); rightFootSensor.localPosition.x = ((entityWidth / 2) - (0.5 * sensorRadius)); rightFootSensor.localPosition.y = (entityHeight + 5); rightFootSensor.radius = sensorRadius; rightFootSensor.isSensor = true; rightFootSensor.userData = rightFootHolder; if (isDebugEnabled){ circleDef = new CircleGraphicDefinition(1000, "leftSensor", leftSensor, 0xFF0000, 0xFF0000); graphic = circleDef.createGraphic(1); entity.addGraphic(graphic); entity.getEngine().renderer.addDisplayObject(graphic.display, EngineRenderer.DEBUG_LAYER); circleDef = new CircleGraphicDefinition(1000, "rightSensor", rightSensor, 0xFF0000, 0xFF0000); graphic = circleDef.createGraphic(1); entity.addGraphic(graphic); entity.getEngine().renderer.addDisplayObject(graphic.display, EngineRenderer.DEBUG_LAYER); }; return ([leftSensor, rightSensor, leftFootSensor, rightFootSensor]); } private function checkPlatform(a_touchEvent:TouchEvent):void{ var leftFootPlaced:Boolean; var rightFootPlaced:Boolean; var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (userData == leftFootHolder){ leftFootDown = true; }; if (userData == rightFootHolder){ rightFootDown = true; }; } override public function tick(a_deltaTime:Number):void{ var viewX:Number; var myX:Number; var edge:Number; var separation:Number; if (m_isFirstTime){ movingLeft = !(this.entity.properties.getBoolean("goRight", false)); m_isFirstTime = false; }; if (!m_activated){ viewX = entity.getEngine().renderer.view.viewX; myX = entity.getPosition().x; edge = 15; if (myX < viewX){ edge = (edge * -1); }; separation = ((myX - edge) - viewX); if (Math.abs(separation) < (Constants.RENDER_WIDTH / 2)){ m_activated = true; }; return; }; if ((this.entity.lookupBehavior("flinch") as FlinchBehavior).isActive){ return; }; var velocityX:Number = 70; if (movingLeft){ velocityX = -(velocityX); }; entity.setVelocity(velocityX, entity.getVelocity().y); if (((!((m_walkSound == null))) && (!(m_walkSoundPlaying)))){ if (m_curWalkSoundTimeOut < m_walkSoundTimeOut){ m_curWalkSoundTimeOut = (m_curWalkSoundTimeOut + a_deltaTime); } else { SoundSystem.instance.playSound(m_walkSound, 1, onWalkSoundComplete); m_curWalkSoundTimeOut = 0; m_walkSoundPlaying = true; }; }; if ((((lastX == entity.getPosition().x)) && ((directionSwapTimeout < 0)))){ if (movingLeft == true){ moveRight(); } else { moveLeft(); }; directionSwapTimeout = 50; }; if (directionSwapTimeout > -1){ directionSwapTimeout--; }; lastX = entity.getPosition().x; if (((leftFootDown) && (!(rightFootDown)))){ moveLeft(); }; if (((rightFootDown) && (!(leftFootDown)))){ moveRight(); }; leftFootDown = false; rightFootDown = false; } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (userData == leftHolder){ if (!a_touchEvent.theirEntity.properties.getBoolean("TILE_MAP", false)){ return; }; moveRight(); }; if (userData == rightHolder){ if (!a_touchEvent.theirEntity.properties.getBoolean("TILE_MAP", false)){ return; }; moveLeft(); }; if (userData == leftFootHolder){ leftFootDown = true; }; if (userData == rightFootHolder){ rightFootDown = true; }; } override public function dispose():void{ } } }//package game.behaviors
Section 199
//PizzaDudeBehavior (game.behaviors.PizzaDudeBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class PizzaDudeBehavior extends Behavior { private var yPosition:Number;// = 0 public function PizzaDudeBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); yPosition = entity.getSpawnInfo().y; } override public function tick(a_deltaTime:Number):void{ var animator:AnimationPlayer; var player:Entity = entity.getEngine().lookupEntity("my_player"); if ((((((entity.getVelocity().x > 0)) && ((entity.getPosition().x > player.getPosition().x)))) || ((((entity.getVelocity().x < 0)) && ((entity.getPosition().x < player.getPosition().x)))))){ animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; if (animator.currentAnimationID != "dropped"){ animator.play("dropped"); }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 200
//RailPlatformBehavior (game.behaviors.RailPlatformBehavior) package game.behaviors { import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class RailPlatformBehavior extends Behavior { private var m_waypoints:Array; public var speed:Number;// = 0.1 private var m_anchor:Point;// = null private var m_waypointTraverseDirection:int;// = 1 public var resetStyle:int;// = 1 public var fixY:Number;// = 4 private var m_touchedIDs:Array; private var m_velocity:Point;// = null private var m_waypointIndex:int;// = 0 public static const REVERSE:int = 1; public function RailPlatformBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ var key:String; var location:String; var splitLoc:Array; var locX:Number; var locY:Number; m_waypoints = []; m_touchedIDs = []; super(a_entity, a_name, a_data); var waypointIndex:int; while (true) { key = ("wp_" + waypointIndex); if (!entity.properties.exists(key)){ break; }; location = entity.properties.getString(key, "0 0"); splitLoc = location.split(" "); locX = splitLoc[0]; locY = splitLoc[1]; addWayPoint(locX, locY); waypointIndex++; }; if (waypointIndex == 0){ throw (new Error("You must set waypoints for the rail behavior. wp_0: '0 10', wp_1 :'50 25'")); }; m_velocity = null; this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onPersist); this.entity.addEventListener(EngineEvent.END_TOUCH, endTouch); } private function updateVelocity():void{ if (m_anchor == null){ m_anchor = entity.getPosition().clone(); }; var activeWayPoint:Point = getActiveWayPoint(); m_velocity = new Point(); m_velocity.x = ((m_anchor.x + activeWayPoint.x) - entity.getPosition().x); m_velocity.y = ((m_anchor.y + activeWayPoint.y) - entity.getPosition().y); m_velocity.normalize(speed); } override public function tick(a_deltaTime:Number):void{ if (m_velocity == null){ updateVelocity(); }; var activeWayPoint:Point = getActiveWayPoint(); var separation:Point = new Point(((m_anchor.x + activeWayPoint.x) - entity.getPosition().x), ((m_anchor.y + activeWayPoint.y) - entity.getPosition().y)); var separationLength:Number = separation.length; var displacement:Point = m_velocity.clone(); displacement.normalize((speed * a_deltaTime)); var reachedWayPoint:Boolean; if (separationLength <= displacement.length){ reachedWayPoint = true; displacement.normalize(separationLength); }; entity.setPosition((entity.getPosition().x + displacement.x), (entity.getPosition().y + displacement.y)); updateTouched(displacement); if (reachedWayPoint){ processArrivedAtWaypoint(); }; } private function forgetTouch(a_entity:Entity):void{ var entityIndex:int = m_touchedIDs.indexOf(a_entity.id); if (entityIndex >= 0){ m_touchedIDs.splice(entityIndex, 1); a_entity.properties.kill("attachX"); a_entity.properties.kill("attachY"); }; } private function updateTouched(a_displacement:Point):void{ var entityID:String; var touchedEntity:Entity; var currentPosition:Point; var e:int = (m_touchedIDs.length - 1); while (e >= 0) { entityID = m_touchedIDs[e]; touchedEntity = entity.getEngine().lookupEntity(entityID); if (touchedEntity == null){ m_touchedIDs.splice(e, 1); } else { currentPosition = touchedEntity.getPosition(); touchedEntity.setPosition((currentPosition.x + a_displacement.x), ((currentPosition.y + a_displacement.y) + fixY)); }; e--; }; } override public function dispose():void{ } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; if (!a_touchEvent.theirShape.GetBody().IsDynamic()){ return; }; if (a_touchEvent.theirEntity == null){ return; }; rememberTouch(a_touchEvent.theirEntity); } private function addWayPoint(a_x:Number, a_y:Number):void{ m_waypoints.push(new Point(a_x, a_y)); } private function endTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; if (!a_touchEvent.theirShape.GetBody().IsDynamic()){ return; }; if (a_touchEvent.theirEntity == null){ return; }; forgetTouch(a_touchEvent.theirEntity); } private function rememberTouch(a_entity:Entity):void{ if (m_touchedIDs.indexOf(a_entity.id) < 0){ m_touchedIDs.push(a_entity.id); }; } private function onPersist(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; if (!a_touchEvent.theirShape.GetBody().IsDynamic()){ return; }; if (a_touchEvent.theirEntity == null){ return; }; rememberTouch(a_touchEvent.theirEntity); } private function processArrivedAtWaypoint():void{ m_waypointIndex = (m_waypointIndex + m_waypointTraverseDirection); if ((((m_waypointIndex >= m_waypoints.length)) || ((m_waypointIndex < 0)))){ switch (resetStyle){ case REVERSE: m_waypointTraverseDirection = (m_waypointTraverseDirection * -1); m_waypointIndex = (m_waypointIndex + m_waypointTraverseDirection); break; default: throw (new Error(("Unsupported reset style: " + resetStyle))); }; }; updateVelocity(); } public function getActiveWayPoint():Point{ return (m_waypoints[m_waypointIndex]); } } }//package game.behaviors
Section 201
//SentryBehavior (game.behaviors.SentryBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class SentryBehavior extends Behavior { public var sensorRange:Number;// = 150 private var m_stickPosition:Point;// = null public var isLinear:Boolean;// = false private var m_stateFunction:Function; private var m_activated:Boolean;// = false private static const MOVE_SPEED:Number = 3; public function SentryBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ m_stateFunction = tickWaiting; super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); m_stickPosition = new Point(this.entity.getSpawnInfo().x, this.entity.getSpawnInfo().y); } private function onTouch(a_touchEvent:TouchEvent):void{ if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity == null){ return; }; if (!a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false)){ return; }; entity.properties.setInt("lives", -1); } override public function dispose():void{ } private function tickNormal(a_deltaTime:Number):void{ var player:Entity = entity.getEngine().lookupEntity("my_player"); if (player == null){ return; }; var currentPosition:Point = entity.getPosition(); var displacement:Point = player.getPosition().subtract(currentPosition); if (displacement.length > MOVE_SPEED){ displacement.normalize(MOVE_SPEED); }; if (isLinear){ displacement.x = -(MOVE_SPEED); displacement.y = 0; }; entity.setPosition((currentPosition.x + displacement.x), (currentPosition.y + displacement.y)); entity.setVelocity(0, 0); if (displacement.x > 0){ entity.flip = false; } else { entity.flip = true; }; } private function tickDead(a_deltaTime:Number):void{ if (m_stickPosition == null){ m_stickPosition = entity.getPosition(); }; entity.setPosition(m_stickPosition.x, m_stickPosition.y); entity.setVelocity(0, 0); } private function testForActivation():void{ var player:Entity = entity.getEngine().lookupEntity("my_player"); var target:Point = player.getPosition(); var myPos:Point = entity.getPosition(); var separation:Point = myPos.subtract(target); if (separation.length <= sensorRange){ activate(); }; } private function tickWaiting(a_deltaTime:Number):void{ entity.flip = true; testForActivation(); entity.setPosition(m_stickPosition.x, m_stickPosition.y); entity.setVelocity(0, 0); } private function activate():void{ if (!isLinear){ SoundSystem.instance.playSound(SoundCache.sentryActivateSound); }; var animationPlayer:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; animationPlayer.play("active"); m_activated = true; m_stateFunction = tickNormal; } override public function tick(a_deltaTime:Number):void{ if (entity.properties.getInt("lives", 0) <= 0){ m_stickPosition = null; m_stateFunction = tickDead; }; m_stateFunction(a_deltaTime); } } }//package game.behaviors
Section 202
//ShredderBehavior (game.behaviors.ShredderBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.utils.*; import Box2D.Collision.Shapes.*; import game.*; public class ShredderBehavior extends Behavior { public var DASH_DISTANCE:int;// = 150 public var PUNCH_DISTANCE:int;// = 55 private var m_kickTarget:Point; private var m_henchman2ID:String; private var m_stateFunc:Function; public var RIGHT_EDGE:int;// = 1000 private var m_jumpAttempts:int; private var m_animationPlayer:AnimationPlayer; public var JUMP_ATTEMPTS:int;// = 3 public var MOVE_SPEED:int;// = 120 public var DASH_SPEED:int;// = 220 public var ATTACK_DELAY:int;// = 24 private var m_henchmenCount:int; public var PUNCH_DAMAGE:int;// = 4 private var m_dashDir:int; private var m_walkTarget:int; public var HENCHMEN_COUNT:int;// = 1 private var m_deltaTime:Number; public var JUMP_SPEED:int;// = 400 public var JUMP_HEIGHT:int;// = 600 private var m_henchman1ID:String; private var m_attackDelay:int; public var HENCHMAN:String;// = "_sword_ninja" public var IS_CLONE:Boolean;// = false public var KICK_SPEED:int;// = 550 private var m_player:Entity; private var m_dashStartX:int; public var LEFT_EDGE:int;// = 500 public function ShredderBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_stateFunc = walkState; m_attackDelay = 0; m_henchmenCount = HENCHMEN_COUNT; m_walkTarget = LEFT_EDGE; } private function jumpState():void{ var diff:int; if (m_animationPlayer.currentAnimationID != "jump"){ diff = (m_player.getPosition().x - this.entity.getPosition().x); this.entity.flip = (diff < 0); m_dashDir = (this.entity.flipped) ? -1 : 1; }; if (this.entity.getPosition().y > JUMP_HEIGHT){ this.entity.setVelocity(0, -(JUMP_SPEED)); } else { m_kickTarget = new Point(m_player.getPosition().x, m_player.properties.getInt("lastSafeY", 790)); SoundSystem.instance.playSound(new ShredderAirDash()); changeState(airKickState); }; play("jump"); } private function punchState():void{ m_animationPlayer.addEventListener(FrameEvent.CHANGE, onPunchFrameChange); m_animationPlayer.addEventListener(AnimationEvent.CHANGE, onPunchChange); play("punch"); } private function onAnimationChanged(a_event:AnimationEvent):void{ var s:b2Shape; var henchman:Entity; if (((a_event.begin) && ((a_event.animationID == "death")))){ s = entity.body.GetShapeList(); while (s != null) { entity.body.DestroyShape(s); s = s.GetNext(); }; entity.body.SetStatic(); SoundSystem.instance.playSound(new HunDie()); henchman = entity.getEngine().lookupEntity(m_henchman1ID); if (henchman != null){ henchman.properties.setInt("lives", 0); }; henchman = entity.getEngine().lookupEntity(m_henchman2ID); if (henchman != null){ henchman.properties.setInt("lives", 0); }; }; if (!IS_CLONE){ if (((!(a_event.begin)) && ((a_event.animationID == "death")))){ m_player.properties.setBoolean("touchedExit", true); }; }; } private function findFarthestEdge():void{ m_walkTarget = LEFT_EDGE; if ((RIGHT_EDGE - this.entity.getPosition().x) > (this.entity.getPosition().x - LEFT_EDGE)){ m_walkTarget = RIGHT_EDGE; }; } private function spawnHenchmen():void{ var hench:Entity; if (hasHenchmen()){ return; }; if (m_henchmenCount > 0){ m_henchmenCount = (m_henchmenCount - 1); } else { findFarthestEdge(); changeState(walkState); return; }; var playerPosition:Point = m_player.getPosition(); m_henchman1ID = ("h" + Math.random()); m_henchman2ID = ("h" + Math.random()); if (HENCHMAN == Constants.ENTITY_TYPE_CLONE_SHREDDER){ hench = entity.getEngine().createEntity(new EntitySpawnInfo(HENCHMAN, m_henchman1ID, entity.getPosition().x, entity.getPosition().y, 0, 0, 0, 1, null, PruneType.IMMUNE)); hench.properties.setBoolean("goRight", true); m_henchman2ID = ""; } else { hench = entity.getEngine().createEntity(new EntitySpawnInfo(HENCHMAN, m_henchman1ID, (LEFT_EDGE + 20), (playerPosition.y - 320), 0, 0, 0, 1, null, PruneType.IMMUNE)); hench.properties.setBoolean("goRight", true); entity.getEngine().createEntity(new EntitySpawnInfo(HENCHMAN, m_henchman2ID, (RIGHT_EDGE - 20), (playerPosition.y - 320), 0)); }; } private function hasHenchmen():Boolean{ if (IS_CLONE){ return (true); }; var henchman:Entity = entity.getEngine().lookupEntity(m_henchman1ID); if (henchman != null){ return (true); }; henchman = entity.getEngine().lookupEntity(m_henchman2ID); if (henchman != null){ return (true); }; return (false); } override public function tick(a_deltaTime:Number):void{ m_deltaTime = a_deltaTime; if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animationPlayer.addEventListener(AnimationEvent.CHANGE, onAnimationChanged, false, 0, true); if (IS_CLONE){ m_animationPlayer.alpha = 0.6; }; }; if (m_player == null){ m_player = entity.getEngine().lookupEntity("my_player"); }; if (this.entity.properties.getInt("lives", 1) <= 0){ return; }; if (m_attackDelay > 0){ m_attackDelay = (m_attackDelay - 1); idleState(); if (m_stateFunc == henchmenState){ play("stun"); }; return; }; m_stateFunc(); } override public function dispose():void{ } private function idleState():void{ this.entity.setVelocity(0, this.entity.getVelocity().y); play("idle"); } private function henchmenState():void{ m_henchmenCount = HENCHMEN_COUNT; spawnHenchmen(); m_attackDelay = ATTACK_DELAY; changeState(chasePlayerState, false); } private function play(a_animId:String):void{ if (((((!((a_animId == m_animationPlayer.currentAnimationID))) && (!((m_animationPlayer.currentAnimationID == "flinch"))))) && (!((m_animationPlayer.currentAnimationID == "death"))))){ m_animationPlayer.play(a_animId); }; } private function onPunchChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animationPlayer.removeEventListener(AnimationEvent.CHANGE, onPunchChange); m_attackDelay = ATTACK_DELAY; changeState(chasePlayerState, false); }; } private function changeState(a_func:Function, a_doChangeNow:Boolean=true):void{ m_stateFunc = a_func; if (a_doChangeNow){ m_stateFunc(); }; } private function walkState():void{ var diff:int = (m_walkTarget - this.entity.getPosition().x); this.entity.flip = (diff < 0); if (Math.abs(diff) < 10){ m_jumpAttempts = JUMP_ATTEMPTS; changeState(jumpState); return; }; var playerDiff:int = (m_player.getPosition().x - this.entity.getPosition().x); if ((((Math.abs(playerDiff) <= DASH_DISTANCE)) && ((((((m_walkTarget == LEFT_EDGE)) && ((playerDiff < 0)))) || ((((m_walkTarget == RIGHT_EDGE)) && ((playerDiff > 0)))))))){ m_dashDir = (this.entity.flipped) ? -1 : 1; m_dashStartX = this.entity.getPosition().x; SoundSystem.instance.playSound(new ShredderSlide()); changeState(dashState); return; }; var xVel:Number = MOVE_SPEED; if (diff < 0){ xVel = -(MOVE_SPEED); }; play("walk"); this.entity.setVelocity(xVel, this.entity.getVelocity().y); } private function airKickState():void{ var sep:Point; if (this.entity.properties.getBoolean("standingOnSomething", false)){ m_jumpAttempts = (m_jumpAttempts - 1); if (m_jumpAttempts > 0){ SoundSystem.instance.playSound(new HunHitWall()); changeState(jumpState, false); return; }; this.entity.getEngine().renderer.view.shakeView(100, 6); m_attackDelay = (ATTACK_DELAY * JUMP_ATTEMPTS); changeState(henchmenState, false); return; } else { sep = m_kickTarget.subtract(this.entity.getPosition()); sep.normalize(KICK_SPEED); this.entity.setVelocity(sep.x, sep.y); }; play("airkick"); } private function chasePlayerState():void{ spawnHenchmen(); var diff:int = (m_player.getPosition().x - this.entity.getPosition().x); this.entity.flip = (diff < 0); if (Math.abs(diff) < PUNCH_DISTANCE){ changeState(punchState); return; }; var xVel:Number = MOVE_SPEED; if (diff < 0){ xVel = -(MOVE_SPEED); }; play("walk"); this.entity.setVelocity(xVel, this.entity.getVelocity().y); } private function dashState():void{ var diff:int = Math.abs((m_dashStartX - this.entity.getPosition().x)); if ((((diff > DASH_DISTANCE)) || (isRunningIntoWall()))){ m_attackDelay = 5; changeState(walkState); return; }; play("dash"); this.entity.setVelocity((DASH_SPEED * m_dashDir), this.entity.getVelocity().y); } private function isRunningIntoWall():Boolean{ return (((this.entity.properties.getBoolean("touchingWall", false)) && ((((((m_dashDir > 0)) && (this.entity.properties.getBoolean("rightWall", true)))) || ((((m_dashDir < 0)) && (this.entity.properties.getBoolean("leftWall", true)))))))); } private function onPunchFrameChange(a_event:FrameEvent):void{ var attackOffsetX:Number; var attackOffsetY:Number; var attackWidth:Number; var attackHeight:Number; var startX:Number; var startY:Number; var boxedEntities:Array; var b:int; if (a_event.frameID == "punch_1"){ m_animationPlayer.removeEventListener(FrameEvent.CHANGE, onPunchFrameChange); attackOffsetX = 10; attackOffsetY = -10; attackWidth = (PUNCH_DISTANCE - 5); attackHeight = 30; startX = (this.entity.getPosition().x + attackOffsetX); startY = (this.entity.getPosition().y + attackOffsetY); if (this.entity.flipped){ startX = ((this.entity.getPosition().x - attackOffsetX) - attackWidth); }; boxedEntities = entity.getEngine().queryBox(startX, startY, attackWidth, attackHeight); b = 0; while (b < boxedEntities.length) { AttackManager.enemyAttack(this.entity, boxedEntities[b], PUNCH_DAMAGE); b++; }; SoundSystem.instance.playSound(new StrongPunchAttack1()); }; } } }//package game.behaviors
Section 203
//ShurikenNinjaBehavior (game.behaviors.ShurikenNinjaBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.utils.*; public class ShurikenNinjaBehavior extends Behavior { public var projectileType:String;// = "aaX" public var offsetX:Number;// = 35 public var offsetY:Number;// = -14 private var m_timer:Number;// = 0 private var m_animationPlayer:AnimationPlayer; private var m_activated:Boolean;// = false private static const TIMER_COOLDOWN:Number = 2000; public function ShurikenNinjaBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } override public function tick(a_deltaTime:Number):void{ if (m_animationPlayer == null){ m_animationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animationPlayer.addEventListener(AnimationEvent.CHANGE, animationChange, false, 0, true); m_animationPlayer.addEventListener(FrameEvent.CHANGE, frameChange, false, 0, true); }; if (entity.properties.getInt("lives", 1) < 0){ return; }; if (!m_activated){ entity.flip = true; testForActivation(); return; }; testForDeactivation(); m_timer = (m_timer - a_deltaTime); if ((this.entity.lookupBehavior("flinch") as FlinchBehavior).isActive){ return; }; if (m_timer <= 0){ trigger(); }; } override public function dispose():void{ } private function testForDeactivation():void{ var viewX:Number = entity.getEngine().renderer.view.viewX; var myX:Number = entity.getPosition().x; var edge:Number = offsetX; if (myX < viewX){ edge = (edge * -1); }; var separation:Number = ((myX - edge) - viewX); if (Math.abs(separation) > (Constants.RENDER_WIDTH / 2)){ m_activated = false; }; } private function animationChange(a_event:AnimationEvent):void{ } private function trigger():void{ var playerX:Number; m_timer = TIMER_COOLDOWN; var player:Entity = entity.getEngine().lookupEntity("my_player"); if (player != null){ playerX = player.getPosition().x; if (playerX > entity.getPosition().x){ entity.flip = false; } else { entity.flip = true; }; }; SoundSystem.instance.playSound(SoundCache.shurikenSound); m_animationPlayer.play("attack"); } private function testForActivation():void{ var viewX:Number = entity.getEngine().renderer.view.viewX; var myX:Number = entity.getPosition().x; var edge:Number = offsetX; if (myX < viewX){ edge = (edge * -1); }; var separation:Number = ((myX - edge) - viewX); if (Math.abs(separation) < (Constants.RENDER_WIDTH / 2)){ m_activated = true; }; } private function frameChange(a_event:FrameEvent):void{ var xVelocity:Number; var myOffsetX:Number; var spawnInfo:EntitySpawnInfo; var spawnedEntity:Entity; if ((((a_event.animationID == "attack")) && ((a_event.frameID == "release")))){ xVelocity = 450; myOffsetX = offsetX; if (entity.flipped){ myOffsetX = (myOffsetX * -1); xVelocity = (xVelocity * -1); }; spawnInfo = new EntitySpawnInfo(projectileType, "", (this.entity.getPosition().x + myOffsetX), (this.entity.getPosition().y + offsetY), xVelocity, -60, 0, 1, null); spawnedEntity = entity.getEngine().createEntity(spawnInfo); spawnedEntity.flip = entity.flipped; }; } } }//package game.behaviors
Section 204
//SlothBehavior (game.behaviors.SlothBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.utils.*; import game.*; public class SlothBehavior extends Behavior { private var m_timer:Number;// = 0 private static const TIMER_COOLDOWN:Number = 2500; public function SlothBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); } private function trigger():void{ var attackAnimation:String = "attack"; var animationPlayer:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; if (animationPlayer.currentAnimationID == attackAnimation){ return; }; if (!animationPlayer.hasEventListener(FrameEvent.CHANGE)){ animationPlayer.addEventListener(FrameEvent.CHANGE, onFrameChange, false, 0, true); }; animationPlayer.play(attackAnimation); m_timer = TIMER_COOLDOWN; } override public function tick(a_deltaTime:Number):void{ var playerSeparationX:Number; var playerSeparationY:Number; if (entity.properties.getInt("lives", 1) < 0){ return; }; m_timer = (m_timer - a_deltaTime); var player:Entity = entity.getEngine().lookupEntity("my_player"); if (player != null){ if (player.getPosition().x < this.entity.getPosition().x){ entity.flip = false; } else { entity.flip = true; }; }; if (m_timer <= 0){ if (player != null){ playerSeparationX = Math.abs((entity.getPosition().x - entity.getEngine().renderer.view.viewX)); playerSeparationY = Math.abs((entity.getPosition().y - entity.getEngine().renderer.view.viewY)); if ((((playerSeparationX < (Constants.RENDER_WIDTH / 2))) && ((playerSeparationY < (Constants.RENDER_HEIGHT / 2))))){ trigger(); }; }; }; } private function onFrameChange(a_frameEvent:FrameEvent):void{ var player:Entity; var animationID:String = a_frameEvent.animationID; if (animationID != "attack"){ return; }; var frameID:String = a_frameEvent.frameID; if (frameID == "pound"){ SoundSystem.instance.playSound(new SlothPound()); entity.getEngine().renderer.view.shakeView(250, 10); player = entity.getEngine().lookupEntity("my_player"); if (player != null){ trace((" hurting playing " + player.properties.getBoolean("standingOnSomething", false))); if (player.properties.getBoolean("standingOnSomething", false)){ trace("Doing damage!"); AttackManager.enemyAttack(this.entity, player, 2); }; }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 205
//SplinterSpecialAttackBehavior (game.behaviors.SplinterSpecialAttackBehavior) package game.behaviors { import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.prophet.utils.*; import game.*; public class SplinterSpecialAttackBehavior extends Behavior { private var m_timer:Number;// = 400 private var m_stateFunction:Function; private var m_animator:AnimationPlayer; private static const FADE_OUT_TIME:Number = 500; private static const DAMAGE_AMOUNT:int = 800; private static const INITIAL_IDLE_TIME:Number = 400; private static const KANJI_TO_ATTACK_TIME:Number = 400; public function SplinterSpecialAttackBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ m_stateFunction = tickIdle; super(a_entity, a_name, a_data); } private function tickKanji(a_deltaTime:Number):void{ var g:int; var graphic:Graphic; m_timer = (m_timer - a_deltaTime); if (m_timer > 0){ return; }; flashScreen(); hurtEverythingOnScreen(); m_animator.defaultAnimationID = "idle"; m_animator.play("idle"); m_stateFunction = tickFadeOut; m_timer = FADE_OUT_TIME; } private function flashScreen():void{ var debugDraw:Sprite = entity.getEngine().renderer.lookupRenderLayer((Constants.ENTITY_DEFAULT_RENDER_LAYER + 50)); var box:Sprite = new Sprite(); box.graphics.beginFill(0xFFFFFF, 0.9); box.x = (entity.getPosition().x - (Constants.RENDER_WIDTH / 2)); box.y = (entity.getPosition().y - (Constants.RENDER_HEIGHT / 2)); box.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); debugDraw.addChild(box); Tweener.addTween(box, {alpha:0, time:0.5, onComplete:debugDraw.removeChild, onCompleteParams:[box]}); } private function hurtEverythingOnScreen():void{ var entityK:Entity; var flinchDir:int; var engine:Engine = entity.getEngine(); var viewX:Number = engine.renderer.view.viewX; var viewY:Number = engine.renderer.view.viewY; var boxedEntities:Array = engine.queryBox((viewX - (Constants.RENDER_WIDTH / 2)), (viewY - (Constants.RENDER_HEIGHT / 2)), Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT, true); var k:int; while (k < boxedEntities.length) { entityK = boxedEntities[k]; if (!entityK.properties.getBoolean("isEnemy", false)){ } else { flinchDir = ((entityK.getPosition().x)>viewX) ? 1 : -1; AttackManager.doTurtleAttack(entityK, DAMAGE_AMOUNT, "none", flinchDir, true); }; k++; }; } private function tickIdle(a_deltaTime:Number):void{ m_timer = (m_timer - a_deltaTime); if (m_timer <= 0){ startKanjiState(); }; } private function tickFadeOut(a_deltaTime:Number):void{ var graphic:Graphic; m_timer = (m_timer - a_deltaTime); if (m_timer <= 0){ this.entity.getEngine().destroyEntity(this.entity.id); return; }; var newAlpha:Number = (m_timer / FADE_OUT_TIME); var g:int; while (g < entity.graphics.length) { graphic = entity.graphics[g]; graphic.display.alpha = newAlpha; g++; }; } private function startKanjiState():void{ var kanjiGinger:AnimationPlayer; var kanjiContainer:Sprite; var graphic:Graphic; m_stateFunction = tickKanji; m_animator.defaultAnimationID = "attack"; m_animator.play("attack"); m_timer = KANJI_TO_ATTACK_TIME; var xPositions:Array = [0, -100, 100]; var yPosition:Array = [-100, 100, 100]; var names:Array = ["kanji_rat", "kanji_attack", "kanji_ninja"]; var p:int; while (p < xPositions.length) { kanjiGinger = GingerFactory.getInstance().instantiate(names[p]); kanjiGinger.x = xPositions[p]; kanjiGinger.y = yPosition[p]; kanjiGinger.play("attack"); kanjiGinger.startSelfTick(33); kanjiContainer = new Sprite(); kanjiContainer.name = ("kanji" + p); kanjiContainer.addChild(kanjiGinger); graphic = new Graphic(kanjiContainer, ("kanji" + p)); entity.getEngine().renderer.addDisplayObject(graphic.display, (Constants.ENTITY_DEFAULT_RENDER_LAYER + 9)); entity.addGraphic(graphic); entity.updateGraphics(0); p++; }; } override public function tick(a_deltaTime:Number):void{ if (m_animator == null){ m_animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; m_animator.play("idle"); m_animator.alpha = 0; Tweener.addTween(m_animator, {alpha:1, time:0.5}); }; m_stateFunction(a_deltaTime); } override public function dispose():void{ } } }//package game.behaviors
Section 206
//StalkPlayerBehavior (game.behaviors.StalkPlayerBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.utils.*; public class StalkPlayerBehavior extends Behavior { private var m_curWalkSoundTimeOut:Number;// = 0 private var m_disabled:Boolean; public var stalkSpeed:int;// = 70 private var m_waitTime:Number; private var m_animator:AnimationPlayer;// = null public function StalkPlayerBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_disabled = false; } override public function enable():void{ if (!m_disabled){ return; }; m_disabled = false; m_waitTime = (Math.random() * 450); } override public function disable():void{ m_disabled = true; } override public function tick(a_deltaTime:Number):void{ if (m_disabled){ return; }; m_waitTime = (m_waitTime - a_deltaTime); if (m_waitTime > 0){ return; }; if (m_animator == null){ m_animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (((!((m_animator == null))) && ((((m_animator.currentAnimationID == "flinch")) || ((m_animator.currentAnimationID == "death")))))){ return; }; var flinchBeh:FlinchBehavior = (this.entity.lookupBehavior("flinch") as FlinchBehavior); if (((!((flinchBeh == null))) && (flinchBeh.isActive))){ return; }; if (this.entity.properties.getInt("lives", 1) <= 0){ return; }; var player:Entity = this.entity.getEngine().lookupEntity("my_player"); var xVel:Number = stalkSpeed; if (player.getPosition().x > this.entity.getPosition().x){ this.entity.flip = false; } else { this.entity.flip = true; xVel = -(xVel); }; var xDiff:Number = Math.abs((player.getPosition().x - this.entity.getPosition().x)); if ((((xDiff < 34)) || ((xDiff > 630)))){ xVel = 0; }; this.entity.setVelocity(xVel, entity.getVelocity().y); } override public function dispose():void{ } } }//package game.behaviors
Section 207
//SwitchBehavior (game.behaviors.SwitchBehavior) package game.behaviors { import com.urbansquall.ginger.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class SwitchBehavior extends Behavior { private var m_collected:Boolean;// = false public function SwitchBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var electricalEntity:Entity; var theirPosition:Point; var separation:Number; if (m_collected){ return; }; if (!a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false)){ return; }; SoundSystem.instance.playSound(new Zap()); m_collected = true; var animationPlayer:AnimationPlayer = (entity.lookupGraphic("image") as GingerGraphic).animationPlayer; animationPlayer.defaultAnimationID = "switched"; animationPlayer.play("switch"); var closestElectricalWall:Entity; var closestElectricalWallDistance:Number = Number.POSITIVE_INFINITY; var myPosition:Point = entity.getPosition(); var electricalWalls:Array = entity.getEngine().getEntitiesWithType(Constants.ENTITY_TYPE_ELECTRICAL_WALL); var e:int; while (e < electricalWalls.length) { electricalEntity = electricalWalls[e]; theirPosition = electricalEntity.getPosition(); separation = theirPosition.subtract(myPosition).length; if (separation < closestElectricalWallDistance){ closestElectricalWall = electricalEntity; closestElectricalWallDistance = separation; }; e++; }; if (electricalEntity != null){ entity.getEngine().destroyEntity(closestElectricalWall.id); }; } override public function dispose():void{ } override public function createShapes():Array{ return (null); } } }//package game.behaviors
Section 208
//SwordNinjaBehavior (game.behaviors.SwordNinjaBehavior) package game.behaviors { import com.urbansquall.ginger.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import flash.utils.*; import Box2D.Common.Math.*; import game.*; public class SwordNinjaBehavior extends Behavior { public var attackSensorWidth:int;// = 106 public var attackHeight:Number;// = 28 private var m_attackSound:Sound;// = null private var m_interval:Number; public var attackWidth:Number;// = 46 public var attackDamage:int;// = 2 public var attackSensorHeight:int;// = 60 private var m_currentState:Function; public var STALL_TIME:int;// = 70 private var m_lastPosition:Number;// = -1 private var m_animator:AnimationPlayer; private var m_stallTime:int; public var attackOffsetX:Number;// = 10 public var attackOffsetY:Number;// = -27 public function SwordNinjaBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); m_currentState = idleState; if (a_data != null){ if (a_data.exists("attackSound")){ m_attackSound = (a_data.getObject("attackSound", null) as Sound); }; }; this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function changeState(a_stateFunc:Function, a_doChangeNow:Boolean=true):void{ m_currentState = a_stateFunc; if (a_doChangeNow){ m_currentState(); }; } private function onAttackFrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; this.entity.properties.setBoolean("isAttacking", true); m_animator.removeEventListener(FrameEvent.CHANGE, onAttackFrameChange); var startX:Number = (this.entity.getPosition().x + attackOffsetX); var startY:Number = (this.entity.getPosition().y + attackOffsetY); if (this.entity.flipped){ startX = ((this.entity.getPosition().x - attackOffsetX) - attackWidth); }; var boxedEntities:Array = entity.getEngine().queryBox(startX, startY, attackWidth, attackHeight); var b:int; while (b < boxedEntities.length) { AttackManager.enemyAttack(this.entity, boxedEntities[b], attackDamage); b++; }; if (m_attackSound != null){ SoundSystem.instance.playSound(m_attackSound); }; } private function windupState():void{ if (m_animator.currentAnimationID == "windup"){ return; }; this.entity.setVelocity(0, this.entity.getVelocity().y); m_animator.addEventListener(AnimationEvent.CHANGE, onWindupChange); m_animator.play("windup"); } private function onWindupChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onWindupChange); changeState(stallState); }; } override public function createShapes():Array{ var attackSensor:PolygonDef = new PolygonDef(); attackSensor.makeCenteredBox((attackSensorWidth / 2), (attackSensorHeight / 2)); attackSensor.isSensor = true; attackSensor.userData = this; return ([attackSensor]); } private function disableStalk():void{ var behavior:Behavior = this.entity.lookupBehavior("stalkPlayer"); if (behavior == null){ return; }; behavior.disable(); } private function stallState():void{ if (m_stallTime <= 0){ m_stallTime = STALL_TIME; } else { m_stallTime = (m_stallTime - m_interval); }; if (m_stallTime <= 0){ changeState(attackState); return; }; m_animator.play("stall"); } private function enableStalk():void{ var behavior:Behavior = this.entity.lookupBehavior("stalkPlayer"); if (behavior == null){ return; }; behavior.enable(); } override public function tick(a_deltaTime:Number):void{ if (m_animator == null){ m_animator = (this.entity.lookupGraphic("image") as GingerGraphic).animationPlayer; }; if (m_animator.currentAnimationID == "death"){ m_animator.removeEventListener(FrameEvent.CHANGE, onAttackFrameChange); m_animator.removeEventListener(AnimationEvent.CHANGE, onAttackChange); m_animator.removeEventListener(AnimationEvent.CHANGE, onWindupChange); return; }; if ((this.entity.lookupBehavior("flinch") as FlinchBehavior).isActive){ m_animator.removeEventListener(FrameEvent.CHANGE, onAttackFrameChange); m_animator.removeEventListener(AnimationEvent.CHANGE, onAttackChange); m_animator.removeEventListener(AnimationEvent.CHANGE, onWindupChange); this.entity.properties.setBoolean("isAttacking", false); changeState(idleState, false); return; }; m_interval = a_deltaTime; m_currentState(); } override public function dispose():void{ } private function onTouch(a_touchEvent:TouchEvent):void{ if (m_currentState != patrolState){ return; }; if (a_touchEvent.theirEntity == null){ return; }; if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity.body.IsStatic()){ return; }; if (a_touchEvent.myShape.GetUserData() != this){ return; }; if (a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false) == false){ return; }; var theirEntity:Entity = a_touchEvent.theirEntity; if (((((!(entity.flipped)) && ((theirEntity.getPosition().x >= entity.getPosition().x)))) || (((entity.flipped) && ((theirEntity.getPosition().x < entity.getPosition().x)))))){ disableStalk(); changeState(windupState); }; } private function idleState():void{ var player:Entity = entity.getEngine().lookupEntity("my_player"); if ((((Math.abs((player.properties.getInt("lastSafeY", player.getPosition().y) - this.entity.getPosition().y)) < 50)) && (!((this.entity.lookupBehavior("stalkPlayer") == null))))){ changeState(patrolState); return; }; var currentPosition:Number = entity.getPosition().x; if ((((Math.abs((m_lastPosition - currentPosition)) > 0.01)) || ((Math.abs(entity.getVelocity().y) > 0)))){ m_lastPosition = currentPosition; if (m_animator.currentAnimationID == "walk"){ return; }; m_animator.play("walk"); } else { m_lastPosition = currentPosition; if (m_animator.currentAnimationID == "idle"){ return; }; m_animator.play("idle"); }; } private function onAttackChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onAttackChange); this.entity.properties.setBoolean("isAttacking", false); changeState(patrolState); }; } private function attackState():void{ if (m_animator.currentAnimationID == "attack"){ return; }; m_animator.addEventListener(FrameEvent.CHANGE, onAttackFrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onAttackChange); m_animator.play("attack"); } private function patrolState():void{ var player:Entity = entity.getEngine().lookupEntity("my_player"); if (Math.abs((player.properties.getInt("lastSafeY", player.getPosition().y) - this.entity.getPosition().y)) >= 100){ disableStalk(); changeState(idleState); return; }; enableStalk(); var currentPosition:Number = entity.getPosition().x; if ((((Math.abs((m_lastPosition - currentPosition)) > 0.01)) || ((Math.abs(entity.getVelocity().y) > 0)))){ m_lastPosition = currentPosition; if (m_animator.currentAnimationID == "walk"){ return; }; m_animator.play("walk"); } else { m_lastPosition = currentPosition; if (m_animator.currentAnimationID == "idle"){ return; }; m_animator.play("idle"); }; } } }//package game.behaviors
Section 209
//TouchPoolBehavior (game.behaviors.TouchPoolBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import game.events.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class TouchPoolBehavior extends Behavior { public var isDebugEnabled:Boolean;// = false private var m_touchedEntities:Array; private var m_touchedSomething:Boolean;// = false public function TouchPoolBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ m_touchedEntities = []; super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } override public function tick(a_deltaTime:Number):void{ if (!m_touchedSomething){ return; }; m_touchedSomething = false; m_touchedEntities.splice(0); } override public function createShapes():Array{ return (null); } private function onTouch(a_touchEvent:TouchEvent):void{ m_touchedSomething = true; if (!a_touchEvent.theirEntity.properties.getBoolean("isTurtle", false)){ if (!a_touchEvent.theirEntity.properties.getBoolean("ignoresBoundaries", false)){ entity.getEngine().destroyEntity(a_touchEvent.theirEntity.id); }; return; }; if (m_touchedEntities.indexOf(a_touchEvent.theirEntity) >= 0){ return; }; entity.getEngine().dispatchEvent(new TouchPoolEvent()); m_touchedEntities.push(a_touchEvent.theirEntity); } override public function dispose():void{ } } }//package game.behaviors
Section 210
//TriggerTutorialPanelBehavior (game.behaviors.TriggerTutorialPanelBehavior) package game.behaviors { import shared.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; import com.urbansquall.prophet.input.*; import game.ui.*; public class TriggerTutorialPanelBehavior extends Behavior { private var m_tutorialLayer:int;// = 10000 private var m_touchCount:int; private var m_tutorialPopup:SpeechBubble;// = null private var m_tutorialText:String; public function TriggerTutorialPanelBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.END_TOUCH, onLeaveTouch); m_tutorialText = a_entity.getSpawnInfo().properties.getString(Constants.DATA_TUTORIAL_TEXT, "Hi there! =)"); m_touchCount = 0; } private function onTouch(a_touchEvent:TouchEvent):void{ var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity.id == "my_player"){ m_touchCount++; if (m_touchCount == 1){ trace(m_tutorialText); if (m_tutorialPopup == null){ m_tutorialPopup = new SpeechBubble(m_tutorialText); m_tutorialPopup.x = int(a_touchEvent.myEntity.getPosition().x); m_tutorialPopup.y = int(a_touchEvent.myEntity.getPosition().y); entity.getEngine().renderer.addDisplayObject(m_tutorialPopup, m_tutorialLayer); }; }; }; } private function onLeaveTouch(a_touchEvent:TouchEvent):void{ var userData:Object = (a_touchEvent.myShape.GetUserData() as Object); if (a_touchEvent.theirShape.IsSensor()){ return; }; if (a_touchEvent.theirEntity.id == "my_player"){ m_touchCount--; if (m_touchCount <= 0){ m_touchCount = 0; if (m_tutorialPopup != null){ entity.getEngine().renderer.removeDisplayObject(m_tutorialPopup); m_tutorialPopup = null; }; }; }; } override public function tick(a_interval:Number):void{ var player:Entity; var keyboardState:KeyboardState; if (m_tutorialPopup != null){ player = entity.getEngine().lookupEntity("my_player"); if (player != null){ keyboardState = entity.getEngine().keyboardState; if (keyboardState.isDown(KeyboardMap.DOWN)){ entity.getEngine().renderer.removeDisplayObject(m_tutorialPopup); m_tutorialPopup = null; m_touchCount = 0; return; }; }; }; } override public function dispose():void{ } } }//package game.behaviors
Section 211
//WallDetectionBehavior (game.behaviors.WallDetectionBehavior) package game.behaviors { import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Common.Math.*; public class WallDetectionBehavior extends Behavior { public var sensorHeight:Number;// = 3 public var drawShapes:Boolean;// = false public var sensorCollisionGroupIndex:int;// = 0 public var sensorOffsetY:Number;// = 0 public var sensorOffsetX:Number;// = 0 public var sensorWidth:Number;// = 3 public var requireGrabbableWalls:Boolean;// = true public function WallDetectionBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); this.entity.addEventListener(EngineEvent.PERSIST_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ var tileDef:TileDefinition; if (a_touchEvent.myShape.GetUserData() == this){ if ((a_touchEvent.theirShape.GetUserData() is TileDefinition)){ tileDef = (a_touchEvent.theirShape.GetUserData() as TileDefinition); if (((!(requireGrabbableWalls)) || (tileDef.properties.getBoolean("grabbable", true)))){ touchWall(a_touchEvent.position); }; }; }; } override public function tick(a_deltaTime:Number):void{ entity.properties.setBoolean("touchingWall", false); } override public function dispose():void{ } private function touchWall(a_contactPosition:b2Vec2):void{ entity.properties.setBoolean("touchingWall", true); if (entity.getPosition().x > a_contactPosition.x){ entity.properties.setBoolean("rightWall", false); entity.properties.setBoolean("leftWall", true); } else { entity.properties.setBoolean("rightWall", true); entity.properties.setBoolean("leftWall", false); }; } override public function createShapes():Array{ var result:Array; var polyDef:PolygonGraphicDefinition; var graphic:Graphic; result = []; var sensor:PolygonDef = new PolygonDef(); sensor.makeCenteredBox((sensorWidth / 2), (sensorHeight / 2), -(sensorOffsetX), sensorOffsetY); sensor.isSensor = true; sensor.userData = this; sensor.groupFilter = sensorCollisionGroupIndex; result.push(sensor); if (drawShapes){ polyDef = new PolygonGraphicDefinition(EngineRenderer.DEBUG_LAYER, "left_wall_sense", sensor, 0xFF0000, 0xFF0000); graphic = polyDef.createGraphic(1); entity.addGraphic(graphic); entity.getEngine().renderer.addDisplayObject(graphic.display, EngineRenderer.DEBUG_LAYER); }; sensor = new PolygonDef(); sensor.makeCenteredBox((sensorWidth / 2), (sensorHeight / 2), sensorOffsetX, sensorOffsetY); sensor.isSensor = true; sensor.userData = this; sensor.groupFilter = sensorCollisionGroupIndex; result.push(sensor); if (drawShapes){ polyDef = new PolygonGraphicDefinition(EngineRenderer.DEBUG_LAYER, "right_wall_sense", sensor, 0xFF0000, 0xFF0000); graphic = polyDef.createGraphic(1); entity.addGraphic(graphic); entity.getEngine().renderer.addDisplayObject(graphic.display, EngineRenderer.DEBUG_LAYER); }; return (result); } } }//package game.behaviors
Section 212
//WeaknessToAcidBehavior (game.behaviors.WeaknessToAcidBehavior) package game.behaviors { import com.urbansquall.prophet.engine.*; import com.urbansquall.prophet.tilemaps.*; import game.events.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.utils.*; public class WeaknessToAcidBehavior extends Behavior { private var m_touchedAcid:Boolean;// = false public function WeaknessToAcidBehavior(a_entity:Entity, a_name:String, a_data:KeyValueMap){ super(a_entity, a_name, a_data); this.entity.addEventListener(EngineEvent.BEGIN_TOUCH, onTouch); } private function onTouch(a_touchEvent:TouchEvent):void{ if (m_touchedAcid){ return; }; if (a_touchEvent.myShape.IsSensor()){ return; }; if (!(a_touchEvent.theirShape.GetUserData() is TileDefinition)){ return; }; var tileDef:TileDefinition = (a_touchEvent.theirShape.GetUserData() as TileDefinition); if (tileDef.properties.getBoolean("acidic", false)){ m_touchedAcid = true; if (entity.properties.getBoolean("isTurtle", false)){ entity.getEngine().dispatchEvent(new TouchPoolEvent()); } else { entity.properties.setInt("lives", 0); }; }; } override public function tick(a_deltaTime:Number):void{ m_touchedAcid = false; } override public function dispose():void{ } } }//package game.behaviors
Section 213
//ChangeScoreEvent (game.events.ChangeScoreEvent) package game.events { import flash.events.*; public class ChangeScoreEvent extends Event { public var amount:int; public var y:int; public var x:int; public static const CHANGE_SCORE:String = "change_score"; public function ChangeScoreEvent(a_amount:int, a_x:int, a_y:int){ super(CHANGE_SCORE); amount = a_amount; x = a_x; y = a_y; } } }//package game.events
Section 214
//ChangeStatisticEvent (game.events.ChangeStatisticEvent) package game.events { import flash.events.*; public class ChangeStatisticEvent extends Event { public var value:int; public var name:String; public static const CHANGE_STAT:String = "change_stat"; public function ChangeStatisticEvent(a_name:String, a_value:int){ super(CHANGE_STAT); name = a_name; value = a_value; } } }//package game.events
Section 215
//ChangeViewTargetEvent (game.events.ChangeViewTargetEvent) package game.events { import com.urbansquall.prophet.engine.*; public class ChangeViewTargetEvent extends EngineEvent { public var targetID:String; public static const CHANGE_VIEW_TARGET:String = "viewTarget"; public function ChangeViewTargetEvent(a_targetID:String){ super(CHANGE_VIEW_TARGET); targetID = a_targetID; } } }//package game.events
Section 216
//ComboEvent (game.events.ComboEvent) package game.events { import flash.events.*; public class ComboEvent extends Event { public static const COMBO_UP:String = "combo_up"; public static const COMBO_RESET:String = "combo_reset"; public function ComboEvent(a_type:String){ super(a_type); } } }//package game.events
Section 217
//TouchPoolEvent (game.events.TouchPoolEvent) package game.events { import com.urbansquall.prophet.engine.*; public class TouchPoolEvent extends EngineEvent { public static const TOUCHED_POOL:String = "touchedpool"; public function TouchPoolEvent(){ super(TOUCHED_POOL); } } }//package game.events
Section 218
//ActiveStatusBox (game.ui.ActiveStatusBox) package game.ui { import flash.display.*; import shared.*; public class ActiveStatusBox extends Sprite { private var s_barYMargin:Number; private var s_barSpacing:Number;// = 1 private var s_barWidth:Number;// = 3 private var m_barHeight:Number;// = 0 private var m_oozeLabel:DefaultTextField;// = null private var s_barStart:Number; private var m_ooze:int;// = 30 private var m_healthToHealthBarRatio:Number;// = 0 private var m_oozeBarContainer:Sprite;// = null private var s_statusElementMargin:Number;// = 3 private var m_healthLabel:DefaultTextField;// = null private var m_health:int;// = 20 private var m_maxNumHealthBars:int;// = 0 private var s_barBorderWidth:Number;// = 1 private var m_oozeToOozeBarRatio:Number;// = 0 private var m_healthBarContainer:Sprite;// = null public function ActiveStatusBox(a_width:Number, a_height:Number){ s_barStart = (s_barBorderWidth + s_barSpacing); s_barYMargin = s_barStart; super(); var sliceOfHeight:Number = (a_height / 4); m_barHeight = ((sliceOfHeight - s_barYMargin) - 1); var outerBarContainerWidth:Number = (a_width - (s_statusElementMargin * 2)); var innerBarContainerWidth:Number = (outerBarContainerWidth - s_barSpacing); m_healthBarContainer = createBarContainer(a_width, outerBarContainerWidth, sliceOfHeight); m_healthBarContainer.x = 0; m_healthBarContainer.y = (sliceOfHeight * 3); addChild(m_healthBarContainer); m_healthLabel = new DefaultTextField("Health", 0xFFFFFF, 14); m_healthLabel.y = (m_healthBarContainer.y - m_healthLabel.height); addChild(m_healthLabel); m_maxNumHealthBars = Math.floor((innerBarContainerWidth / (s_barWidth + s_barSpacing))); m_healthToHealthBarRatio = (m_maxNumHealthBars / Constants.STARTING_HEALTH); setHealth(m_health); } private function createBarContainer(a_width:Number, a_outerBarContainerWidth:Number, a_sliceOfHeight:Number):Sprite{ var barContainer:Sprite = new Sprite(); barContainer = new Sprite(); barContainer.graphics.lineStyle(1, 0xFFFFFF); barContainer.graphics.beginFill(0); barContainer.graphics.drawRect(0, 0, a_outerBarContainerWidth, a_sliceOfHeight); barContainer.graphics.endFill(); return (barContainer); } private function calculateBars(a_num:int, a_ratio:Number):int{ var numBars:int = Math.floor((a_num * a_ratio)); if ((((numBars == 0)) && ((a_num > 0)))){ numBars = 1; }; return (numBars); } private function drawBars(barContainer:Sprite, numBars:int, a_color:uint):void{ var bar:Sprite; var curBarX:Number = s_barStart; var barIndex:int; while (barIndex < numBars) { bar = new Sprite(); bar.graphics.beginFill(a_color, 1); bar.graphics.drawRect(0, 0, s_barWidth, m_barHeight); bar.graphics.endFill(); bar.x = curBarX; bar.y = s_barStart; curBarX = (curBarX + (bar.width + s_barSpacing)); barContainer.addChild(bar); barIndex++; }; } private function eraseBars(barContainer:Sprite):void{ var i:int = barContainer.numChildren; while (i--) { barContainer.removeChildAt(i); }; } public function setHealth(a_health:int):void{ m_health = a_health; eraseBars(m_healthBarContainer); drawBars(m_healthBarContainer, calculateBars(m_health, m_healthToHealthBarRatio), 0xFF0000); } } }//package game.ui
Section 219
//CampaignScreen (game.ui.CampaignScreen) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.engine.*; import flash.text.*; import com.urbansquall.audio.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.ui.levelscreen.*; import com.urbansquall.prophet.tilemaps.editor.*; import flash.utils.*; import game.*; import flash.net.*; import flash.filters.*; public class CampaignScreen extends Sprite { private var m_levelDescriptionBox:Sprite;// = null private var m_levelDescriptionTextField:DefaultTextField;// = null private var m_game:Game;// = null private var m_progress:int;// = 0 private var m_fullVersionButton:VistaButton; private var m_levelDescriptionTitleTextField:DefaultTextField;// = null private var m_leavePopupButton:VistaButton; private var m_editMode:Boolean; private var m_lastPlayedLevel:int; private var m_levelSelected:int;// = -1 private var m_levelSelector:LevelSelector; private var m_storyData:StoryData; private var m_uiContainer:Sprite;// = null private var m_editor:LevelEditor;// = null private static var LEVEL_DESCRIPTION_BOX_MARGIN:Number = 15; private static var s_secondaryCharacter:String = "Donatello"; private static var s_primaryCharacter:String = "Leonardo"; private static var LEVEL_DESCRIPTION_BOX_WIDTH:Number = 280; private static var LEVEL_DESCRIPTION_BOX_HEIGHT:Number = 190; public static var LEVEL_COUNT:int = 15; public function CampaignScreen(a_editMode:Boolean=false){ m_storyData = new StoryData(); super(); m_editMode = a_editMode; m_progress = SafeSol.instance.readInt("maxLevel"); if (Constants.ALLOW_DEBUG){ LEVEL_COUNT = 16; m_progress = LEVEL_COUNT; }; if (m_editMode){ m_progress = LEVEL_COUNT; }; if (Constants.UNLOCK_ALL){ m_progress = LEVEL_COUNT; }; addEventListener(Event.ADDED_TO_STAGE, redraw, false, 0, true); } private function complete(a_event:Event):void{ var level:XML; if (m_game != null){ if (m_game.playerWon){ m_lastPlayedLevel++; if (m_progress < m_lastPlayedLevel){ m_progress = m_lastPlayedLevel; }; if (m_progress >= LEVEL_COUNT){ m_progress = LEVEL_COUNT; }; SafeSol.instance.writeInt("maxLevel", m_progress); }; m_game.dispose(); removeChild(m_game); m_game = null; }; if (m_editor != null){ level = m_editor.exportXML(); LevelData.writeLevel(m_levelSelected, level); m_editor.dispose(); removeChild(m_editor); m_editor = null; }; this.stage.focus = this.stage; redraw(); } protected function editLevel(a_index:int):void{ m_editor = new LevelEditor(new TMNTGameDefinition(), new TMNTTileLibrary(), [2, 1, 0]); m_editor.addEventListener(Event.COMPLETE, complete, false, 0, true); addChild(m_editor); var levelXML:XML = LevelData.readLevel(a_index); m_editor.load(levelXML); } private function handleCutSceneFinished(e:Event):void{ this.stage.focus = this.stage; redraw(); } private function clickBack(a_event:MouseEvent):void{ if (((((Constants.ALLOW_DEBUG) && (a_event.ctrlKey))) && (a_event.altKey))){ m_progress = LEVEL_COUNT; redraw(); return; }; this.dispatchEvent(new Event(Event.COMPLETE)); } private function startLevel(a_index:int, a_primaryCharacter:String, a_secondaryCharacter:String):void{ m_lastPlayedLevel = a_index; var gameDef:GameDefinition = new TMNTGameDefinition(); m_game = new Game(gameDef); m_game.addEventListener(Event.COMPLETE, complete, false, 0, true); m_game.addEventListener(Event.CHANGE, change, false, 0, true); addChild(m_game); var levelDef:LevelDefinition = new LevelDefinition(); levelDef.getDataDump().setString(Constants.DATA_SELECTED_PRIMARY, a_primaryCharacter); levelDef.getDataDump().setString(Constants.DATA_SELECTED_SECONDARY, a_secondaryCharacter); levelDef.getDataDump().setInt(Constants.DATA_LEVEL_INDEX, a_index); m_game.load(levelDef); } protected function playLevel(a_index:int):void{ var fullversionPopup:Sprite; var backToGameY:int; var backToGameX:int; var popup:Popup; var mypopup:Popup; var i:int; var lockedContent:TextField; var label:TextField; if (Constants.LITE_VERSION){ if (a_index >= 5){ if (getChildByName("fullVersionPopup") != null){ mypopup = (getChildByName("fullVersionPopup") as Popup); i = (mypopup.numChildren - 1); while (i >= 0) { mypopup.removeChildAt(i); trace("removing"); i--; }; mypopup.visible = false; mypopup = null; }; fullversionPopup = new Sprite(); backToGameY = 0; backToGameX = 0; if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ lockedContent = new DefaultTextField("Please play the full version"); lockedContent.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; fullversionPopup.addChild(lockedContent); m_fullVersionButton = TMNTButtonFactory.instance.createButton("Click here to play"); m_fullVersionButton.width = 200; m_fullVersionButton.height = 60; m_fullVersionButton.x = int(((fullversionPopup.width / 2) - (m_fullVersionButton.width / 2))); m_fullVersionButton.y = int(((lockedContent.y + lockedContent.height) + 10)); backToGameX = m_fullVersionButton.x; backToGameY = ((m_fullVersionButton.y + m_fullVersionButton.height) + 11); m_fullVersionButton.addEventListener(MouseEvent.CLICK, clickLink); fullversionPopup.addChild(m_fullVersionButton); } else { label = new DefaultTextField("Please play the full version at www.tmntgame.com/US"); label.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; fullversionPopup.addChild(label); label.x = int(((fullversionPopup.width / 2) - (label.width / 2))); label.y = 0; backToGameX = label.x; backToGameY = ((label.y + label.height) + 11); }; m_leavePopupButton = TMNTButtonFactory.instance.createButton("Back to game"); m_leavePopupButton.width = 200; m_leavePopupButton.height = 60; m_leavePopupButton.x = backToGameX; m_leavePopupButton.y = backToGameY; m_leavePopupButton.addEventListener(MouseEvent.CLICK, killPopup); fullversionPopup.addChild(m_leavePopupButton); popup = new Popup(fullversionPopup); popup.addEventListener(MouseEvent.CLICK, killPopup); popup.name = "fullVersionPopup"; addChild(popup); return; }; }; var characterSelectScreen:CharacterSelectScreen = new CharacterSelectScreen(a_index, s_primaryCharacter, s_secondaryCharacter); characterSelectScreen.name = "characterSelect"; characterSelectScreen.addEventListener(Event.COMPLETE, doPlayLevel, false, 0, true); characterSelectScreen.addEventListener(Event.CANCEL, cancelPlayLevel, false, 0, true); addChild(characterSelectScreen); } private function showLevelDescriptionBox(levelIndex:int):void{ if (levelIndex >= Constants.LEVEL_DESCRIPTIONS.length){ return; }; if (levelIndex > m_progress){ return; }; var levelNum:int = (levelIndex + 1); var maxLevelDescriptionTextField:Number = (LEVEL_DESCRIPTION_BOX_WIDTH - (LEVEL_DESCRIPTION_BOX_MARGIN * 2)); m_levelDescriptionTitleTextField.wordWrap = false; m_levelDescriptionTextField.wordWrap = false; m_levelDescriptionTitleTextField.text = ((("Level " + levelNum.toString()) + ": ") + Constants.LEVEL_DESCRIPTIONS[levelIndex].title); if (m_levelDescriptionTitleTextField.width > maxLevelDescriptionTextField){ m_levelDescriptionTitleTextField.wordWrap = true; }; m_levelDescriptionTitleTextField.center(); m_levelDescriptionTitleTextField.x = (((maxLevelDescriptionTextField / 2) - (m_levelDescriptionTitleTextField.width / 2)) + LEVEL_DESCRIPTION_BOX_MARGIN); m_levelDescriptionTitleTextField.y = 10; m_levelDescriptionTextField.text = Constants.LEVEL_DESCRIPTIONS[levelIndex].description; if (m_levelDescriptionTextField.width > maxLevelDescriptionTextField){ m_levelDescriptionTextField.wordWrap = true; m_levelDescriptionTextField.width = maxLevelDescriptionTextField; }; m_levelDescriptionTextField.height = (LEVEL_DESCRIPTION_BOX_HEIGHT - m_levelDescriptionTitleTextField.height); m_levelDescriptionTextField.x = (((maxLevelDescriptionTextField / 2) - (m_levelDescriptionTextField.width / 2)) + LEVEL_DESCRIPTION_BOX_MARGIN); m_levelDescriptionTextField.y = ((m_levelDescriptionTitleTextField.y + m_levelDescriptionTitleTextField.height) + 20); m_levelDescriptionBox.visible = true; } private function change(a_event:Event):void{ complete(null); removeChild(m_uiContainer); m_uiContainer = null; playLevel(m_lastPlayedLevel); } private function cleanup(a_event:Event):void{ this.removeEventListener(Event.REMOVED_FROM_STAGE, cleanup); this.stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); } private function cancelPlayLevel(a_event:Event):void{ var characterSelectScreen:CharacterSelectScreen = (a_event.currentTarget as CharacterSelectScreen); characterSelectScreen.parent.removeChild(characterSelectScreen); complete(null); } private function drawStoryNodes(startX:Number, startY:Number, spacing:Number, a_cols:int, a_rows:int, a_levelNodeWidth:Number, a_levelNodeHeight:Number):void{ var colIndex:int; var curLevelIndex:int; var stories:Array; var story:Story; var storyNode:StoryNode; var curX:Number = startX; var curY:Number = startY; var rowIndex:int; while (rowIndex < a_rows) { colIndex = 0; while (colIndex < a_cols) { curLevelIndex = ((rowIndex * a_cols) + colIndex); stories = m_storyData.stories; for each (story in stories) { if ((story.levelNum - 1) == curLevelIndex){ if (story.movieClipClass == null){ } else { storyNode = new StoryNode(story, playStory); storyNode.x = story.x; storyNode.y = story.y; m_levelSelector.addChild(storyNode); if (m_progress >= (story.levelNum - 1)){ storyNode.enable(); if (m_progress == (story.levelNum - 1)){ if (!story.wasForcedToPlay){ story.forcePlay(); storyNode.onClick(null); }; }; }; }; }; }; curX = (curX + spacing); colIndex++; }; curX = startX; curY = (curY + spacing); rowIndex++; }; } private function playStory(a_story:Story):void{ var storyScreen:StoryScreen; this.stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); removeChild(m_uiContainer); m_uiContainer = null; var storyClass:Class = a_story.movieClipClass; if (storyClass != null){ storyScreen = new StoryScreen(new (storyClass)); storyScreen.addEventListener(Event.COMPLETE, handleCutSceneFinished); addChild(storyScreen); }; } private function doPlayLevel(a_event:Event):void{ var characterSelectScreen:CharacterSelectScreen = (a_event.currentTarget as CharacterSelectScreen); characterSelectScreen.parent.removeChild(characterSelectScreen); var levelIndex:int = characterSelectScreen.levelIndex; s_primaryCharacter = characterSelectScreen.selectedTurtle; s_secondaryCharacter = characterSelectScreen.secondaryCharacter; startLevel(levelIndex, s_primaryCharacter, s_secondaryCharacter); } private function killPopup(a_event:Event):void{ var popup:Popup = (getChildByName("fullVersionPopup") as Popup); if (popup != null){ popup.parent.removeChild(popup); }; complete(null); } private function selectLevel(a_event:LevelSelectEvent):void{ removeChild(m_uiContainer); m_uiContainer = null; var index:int = a_event.index; m_levelSelected = index; if (m_editMode){ editLevel(index); } else { playLevel(index); }; } private function outOfLevelNode(a_event:LevelNodeOutEvent):void{ hideLevelDescriptionBox(); } private function redraw(a_event:Event=null):void{ var editWarningText:TextField; var node:Node; var musicClass:Class; var a_event = a_event; removeEventListener(Event.ADDED_TO_STAGE, redraw, false); if (m_uiContainer != null){ removeChild(m_uiContainer); }; m_uiContainer = new Sprite(); addChild(m_uiContainer); m_uiContainer.addChild(new AssetLibrary.CAMPAIGN_SCREEN()); m_levelDescriptionBox = new Sprite(); m_levelDescriptionBox.graphics.lineStyle(1, 0xFFFFFF); m_levelDescriptionBox.graphics.beginFill(0, 0.7); m_levelDescriptionBox.graphics.drawRoundRect(0, 0, LEVEL_DESCRIPTION_BOX_WIDTH, LEVEL_DESCRIPTION_BOX_HEIGHT, 10, 10); m_levelDescriptionBox.graphics.endFill(); m_levelDescriptionBox.visible = false; m_levelDescriptionBox.x = 360; m_levelDescriptionBox.y = 90; m_levelDescriptionTitleTextField = new DefaultTextField(); m_levelDescriptionTextField = new DefaultTextField(); m_levelDescriptionBox.addChild(m_levelDescriptionTitleTextField); m_levelDescriptionBox.addChild(m_levelDescriptionTextField); m_uiContainer.addChild(m_levelDescriptionBox); if (m_editMode){ editWarningText = new DefaultTextField(); editWarningText.text = "EDIT MODE"; m_uiContainer.addChild(editWarningText); }; var pressAnyKeyLabel:TextField = new DefaultTextField("Press Any Key To Continue", 0xFFFFFF); pressAnyKeyLabel.filters = [new GlowFilter(0, 2, 2, 1, 10, 3), new DropShadowFilter()]; pressAnyKeyLabel.x = ((Constants.RENDER_WIDTH / 2) - (pressAnyKeyLabel.width / 2)); pressAnyKeyLabel.y = (Constants.RENDER_HEIGHT - pressAnyKeyLabel.height); m_uiContainer.addChild(pressAnyKeyLabel); m_levelSelector = new LevelSelector(m_progress, LEVEL_COUNT, new CampaignScreenNodeCreator()); m_levelSelector.addEventListener(LevelSelectEvent.LEVEL_SELECT, selectLevel, false, 0, true); m_levelSelector.addEventListener(LevelNodeOverEvent.LEVEL_OVER, overLevelNode, false, 0, true); m_levelSelector.addEventListener(LevelNodeOutEvent.LEVEL_OUT, outOfLevelNode, false, 0, true); m_levelSelector.buildNodeGrid(50, 50, 4, 4); m_levelSelector.moveNode(0, 69, 42); m_levelSelector.moveNode(1, 121, 42); m_levelSelector.moveNode(2, 172, 45); m_levelSelector.moveNode(3, 217, 47); m_levelSelector.moveNode(4, 288, 85); m_levelSelector.moveNode(5, 265, 118); m_levelSelector.moveNode(6, 250, 162); m_levelSelector.moveNode(7, 213, 194); m_levelSelector.moveNode(8, 208, 248); m_levelSelector.moveNode(9, 290, 316); m_levelSelector.moveNode(10, 333, 330); m_levelSelector.moveNode(11, 379, 342); m_levelSelector.moveNode(12, 426, 349); m_levelSelector.moveNode(13, 492, 355); m_levelSelector.moveNode(14, 557, 359); m_levelSelector.moveNode(15, (Constants.RENDER_WIDTH - 50), 50); if (!Constants.ALLOW_DEBUG){ node = m_levelSelector.getNode(15); if (node != null){ node.visible = false; }; }; m_uiContainer.addChild(m_levelSelector); var backButton:VistaButton = TMNTButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.y = (this.stage.stageHeight - backButton.height); m_uiContainer.addChild(backButton); SoundSystem.instance.destroyLoop("background"); if (((!(SoundSystem.instance.isPlaying("ui_background"))) && (Constants.MUSIC_ENABLED))){ musicClass = (getDefinitionByName("MUSIC_UI") as Class); //unresolved jump var _slot1 = e; musicClass = null; if (musicClass != null){ SoundSystem.instance.createLoop("ui_background", new (musicClass)); } else { SoundSystem.instance.createLoop("ui_background", new MUSIC_IN_GAME()); }; }; this.stage.focus = this.stage; this.stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); this.addEventListener(Event.REMOVED_FROM_STAGE, cleanup); drawStoryNodes(50, 50, 100, 5, 4, 50, 50); } private function hideLevelDescriptionBox():void{ m_levelDescriptionBox.visible = false; } private function overLevelNode(a_event:LevelNodeOverEvent):void{ showLevelDescriptionBox(a_event.index); } private function clickLink(a_e:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_SITE_LINK); navigateToURL(target, "_blank"); } private function keyUp(a_event:KeyboardEvent):void{ if (((!((m_game == null))) || (!((m_editor == null))))){ return; }; if (getChildByName("characterSelect") != null){ return; }; if (getChildByName("fullVersionPopup") != null){ return; }; var level:int = m_progress; if (m_progress >= LEVEL_COUNT){ level = (LEVEL_COUNT - 1); }; if (m_uiContainer != null){ removeChild(m_uiContainer); }; m_uiContainer = null; playLevel(level); } } }//package game.ui
Section 220
//CampaignScreenNodeCreator (game.ui.CampaignScreenNodeCreator) package game.ui { import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.ui.levelscreen.*; public class CampaignScreenNodeCreator implements INodeCreator { private static const s_bossLevels:Array = [5, 10, 15]; private static const s_combatLevels:Array = [3, 8, 13]; public function CampaignScreenNodeCreator(){ super(); } public function createNode(a_levelIndex:int, a_status:String):Node{ var node:Node = new Node(createUnlockedAndNotFinishedNodeImage(a_levelIndex), createUnlockedAndFinishedNodeImage(a_levelIndex), createLockedNodeImage(a_levelIndex), a_status, a_levelIndex); return (node); } private function createMarker(a_levelIndex:int):AnimationPlayer{ var ginger:AnimationPlayer = GingerFactory.getInstance().instantiate("level_marker"); ginger.play(determineGingerAnimation(a_levelIndex)); return (ginger); } private function determineGingerAnimation(a_levelIndex:int):String{ if (s_bossLevels.indexOf((a_levelIndex + 1)) >= 0){ return ("boss"); }; if (s_combatLevels.indexOf((a_levelIndex + 1)) >= 0){ return ("combat"); }; return ("platformer"); } public function createLockedNodeImage(a_levelIndex:int):DisplayObject{ var container:Sprite = new Sprite(); container.alpha = 0.5; var ginger:AnimationPlayer = createMarker(a_levelIndex); container.addChild(ginger); var checkmark:DisplayObject = new AssetLibrary.LEVEL_LOCK(); checkmark.x = -6; checkmark.y = -19; container.addChild(checkmark); return (container); } public function createUnlockedAndNotFinishedNodeImage(a_levelIndex:int):DisplayObject{ var container:Sprite = new Sprite(); var ginger:AnimationPlayer = createMarker(a_levelIndex); var tweenWrap:TweenWrapper = new TweenWrapper(ginger); container.addChild(tweenWrap); TMNTToolTip.attachToolTip(container, ("Level " + (a_levelIndex + 1))); return (container); } public function createUnlockedAndFinishedNodeImage(a_levelIndex:int):DisplayObject{ var container:Sprite = new Sprite(); var ginger:AnimationPlayer = createMarker(a_levelIndex); container.addChild(ginger); var checkmark:DisplayObject = new AssetLibrary.LEVEL_CHECKMARK(); checkmark.x = -8; checkmark.y = -15; container.addChild(checkmark); TMNTToolTip.attachToolTip(container, ("Level " + (a_levelIndex + 1))); return (container); } } }//package game.ui import flash.events.*; import flash.display.*; import caurina.transitions.*; class TweenWrapper extends Sprite { private function TweenWrapper(a_child:DisplayObject){ super(); this.addChild(a_child); this.addEventListener(Event.REMOVED_FROM_STAGE, cleanup); this.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver); this.addEventListener(MouseEvent.MOUSE_OUT, onMouseLeave); tweenDown(); } private function onMouseLeave(a_event:Event):void{ tweenDown(); } private function cleanup(a_event:Event):void{ this.removeEventListener(Event.REMOVED_FROM_STAGE, cleanup); Tweener.removeTweens(this); } private function tweenUp():void{ Tweener.addTween(this, {scaleX:1, scaleY:1, time:0.25, transition:"linear", onComplete:tweenDown, onCompleteParams:[]}); } private function onMouseOver(a_event:Event):void{ scaleX = 1; scaleY = 1; Tweener.removeTweens(this); } private function tweenDown():void{ Tweener.addTween(this, {scaleX:0.8, scaleY:0.8, delay:0.4, time:0.5, onComplete:tweenUp, onCompleteParams:[]}); } }
Section 221
//CharacterSelectScreen (game.ui.CharacterSelectScreen) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.ui.levelscreen.*; import com.urbansquall.display.*; import flash.utils.*; import game.*; import flash.filters.*; public class CharacterSelectScreen extends Sprite { private var m_levelIndex:int; private var m_charactSelectTitleTextField:DefaultTextField;// = null private var m_selectedTurtle:String; private var m_specialCharacterAttackDescriptionTextField:DefaultTextField;// = null private var m_attackDescriptionsDict:Dictionary; private var m_characterPortraitContainer:DisplayObjectContainer;// = null private var m_characterAttackDescriptionTextField:DefaultTextField;// = null private var m_turtleNames:Array; private var m_turltePortraits:Array; private var m_secondaryCharacter:String; private var m_characterNameTextField:DefaultTextField;// = null private var m_uiContainer:Sprite;// = null private var m_specialAttackDescriptionsDict:Dictionary; private static const s_selectPrimaryCharacterText:String = "Select Your Main Character"; private static const s_potraitContainerMargin:Number = 10; private static const s_fontSize:int = 18; public function CharacterSelectScreen(a_levelIndex:int, a_primaryCharacter:String, a_secondaryCharacter:String){ m_attackDescriptionsDict = new Dictionary(); m_specialAttackDescriptionsDict = new Dictionary(); super(); m_selectedTurtle = a_primaryCharacter; m_secondaryCharacter = a_secondaryCharacter; if ((((m_secondaryCharacter == null)) || ((m_secondaryCharacter == "")))){ m_secondaryCharacter = Constants.CHARACTER_RAPHAEL; if (m_selectedTurtle == m_secondaryCharacter){ m_secondaryCharacter = Constants.CHARACTER_LEONARDO; }; }; m_levelIndex = a_levelIndex; m_turltePortraits = [AssetLibrary.PORTRAIT_LEONARDO, AssetLibrary.PORTRAIT_RAPHAEL, AssetLibrary.PORTRAIT_DONATELLO, AssetLibrary.PORTRAIT_MICHELANGELO]; m_turtleNames = [Constants.CHARACTER_LEONARDO, Constants.CHARACTER_RAPHAEL, Constants.CHARACTER_DONATELLO, Constants.CHARACTER_MICHELANGELO]; m_attackDescriptionsDict[Constants.CHARACTER_LEONARDO] = Constants.CHARACTER_ATTACK_DESCRIPTION_LEONARDO; m_attackDescriptionsDict[Constants.CHARACTER_RAPHAEL] = Constants.CHARACTER_ATTACK_DESCRIPTION_RAPHAEL; m_attackDescriptionsDict[Constants.CHARACTER_DONATELLO] = Constants.CHARACTER_ATTACK_DESCRIPTION_DONATELLO; m_attackDescriptionsDict[Constants.CHARACTER_MICHELANGELO] = Constants.CHARACTER_ATTACK_DESCRIPTION_MICHELANGELO; m_specialAttackDescriptionsDict[Constants.CHARACTER_LEONARDO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_LEONARDO; m_specialAttackDescriptionsDict[Constants.CHARACTER_RAPHAEL] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_RAPHAEL; m_specialAttackDescriptionsDict[Constants.CHARACTER_DONATELLO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_DONATELLO; m_specialAttackDescriptionsDict[Constants.CHARACTER_MICHELANGELO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_MICHELANGELO; m_specialAttackDescriptionsDict[Constants.CHARACTER_SPLINTER] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_SPLINTER; m_specialAttackDescriptionsDict[Constants.CHARACTER_CASEY_JONES] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_CASEY_JONES; m_specialAttackDescriptionsDict[Constants.CHARACTER_PIZZA_DUDE] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_PIZZA_DUDE; redraw(); } public function get levelIndex():int{ return (m_levelIndex); } private function click(a_e:Event):void{ m_selectedTurtle = a_e.currentTarget.name; m_uiContainer.visible = false; var secondaryCharacterScreen:SecondaryCharacterSelectScreen = new SecondaryCharacterSelectScreen(m_selectedTurtle, m_secondaryCharacter); addChild(secondaryCharacterScreen); secondaryCharacterScreen.addEventListener(Event.COMPLETE, completeSecondaryCharacter, false, 0, true); secondaryCharacterScreen.addEventListener(Event.CANCEL, cancelSecondaryCharacter, false, 0, true); } private function movedOutOfPortrait(a_event:MouseEvent):void{ var portrait:DisplayObject = (a_event.target as DisplayObject); showCharacterName(""); showCharacterAttackDescription(""); showCharacterSpecialAttackDescription(""); portrait.filters = [new DropShadowFilter()]; } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 400; }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.center(); textfield.width = a_width; addChild(textfield); return (textfield); } private function showCharacterName(a_characterName:String):void{ m_characterNameTextField.text = a_characterName; m_characterNameTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_characterNameTextField.width / 2)); m_characterNameTextField.y = ((m_characterPortraitContainer.y + m_characterPortraitContainer.height) + s_potraitContainerMargin); } public function get secondaryCharacter():String{ return (m_secondaryCharacter); } private function movedOverPortrait(a_event:MouseEvent):void{ var portrait:DisplayObject = (a_event.target as DisplayObject); portrait.filters = [new GlowFilter(0xFFFFFF), new DropShadowFilter()]; showCharacterName(portrait.name); showCharacterAttackDescription(m_attackDescriptionsDict[portrait.name]); showCharacterSpecialAttackDescription(m_specialAttackDescriptionsDict[portrait.name]); } private function showCharacterAttackDescription(a_attackDescription:String):void{ m_characterAttackDescriptionTextField.text = a_attackDescription; m_characterAttackDescriptionTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_characterNameTextField.width / 2)); m_characterAttackDescriptionTextField.y = ((m_characterNameTextField.y + m_characterNameTextField.height) + s_potraitContainerMargin); } private function showCharacterSpecialAttackDescription(a_specialAttackDescription:String):void{ if (a_specialAttackDescription != ""){ a_specialAttackDescription = ("Special Attack: " + a_specialAttackDescription); }; m_specialCharacterAttackDescriptionTextField.text = a_specialAttackDescription; m_specialCharacterAttackDescriptionTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_specialCharacterAttackDescriptionTextField.width / 2)); m_specialCharacterAttackDescriptionTextField.y = (m_characterAttackDescriptionTextField.y + m_characterAttackDescriptionTextField.height); } private function cancelSecondaryCharacter(a_event:Event):void{ m_uiContainer.visible = true; var secondaryCharacterScreen:SecondaryCharacterSelectScreen = (a_event.currentTarget as SecondaryCharacterSelectScreen); secondaryCharacterScreen.parent.removeChild(secondaryCharacterScreen); m_charactSelectTitleTextField.text = s_selectPrimaryCharacterText; } private function clickBack(a_event:Event):void{ this.dispatchEvent(new Event(Event.CANCEL)); } private function completeSecondaryCharacter(a_event:Event):void{ var secondaryCharacterScreen:SecondaryCharacterSelectScreen = (a_event.currentTarget as SecondaryCharacterSelectScreen); m_secondaryCharacter = secondaryCharacterScreen.secondaryCharacter; secondaryCharacterScreen.parent.removeChild(secondaryCharacterScreen); this.dispatchEvent(new Event(Event.COMPLETE)); } private function redraw():void{ var portraitClass:Class; var portrait:Sprite; if (m_uiContainer != null){ removeChild(m_uiContainer); }; m_uiContainer = new Sprite(); addChild(m_uiContainer); var panelData:DisplayObject = new AssetLibrary.PANEL(); var tile9Rect:Rectangle = new Rectangle(12, 12, 22, 22); var tile9Data:Tile9Data = new Tile9Data(panelData, tile9Rect); var tile9:Tile9 = new Tile9(tile9Data); var bgWidth:Number = 600; var bgHeight:Number = 215; tile9.width = bgWidth; tile9.height = bgHeight; tile9.x = ((Constants.RENDER_WIDTH / 2) - (bgWidth / 2)); tile9.y = ((Constants.RENDER_HEIGHT / 2) - (150 / 2)); m_uiContainer.addChild(tile9); m_characterPortraitContainer = new Sprite(); m_uiContainer.addChild(m_characterPortraitContainer); m_charactSelectTitleTextField = createTextField(s_selectPrimaryCharacterText, (s_fontSize + 2)); m_uiContainer.addChild(m_charactSelectTitleTextField); m_characterNameTextField = createTextField("", s_fontSize); m_uiContainer.addChild(m_characterNameTextField); m_characterAttackDescriptionTextField = createTextField("", s_fontSize); m_uiContainer.addChild(m_characterAttackDescriptionTextField); m_specialCharacterAttackDescriptionTextField = createTextField("", s_fontSize); m_uiContainer.addChild(m_specialCharacterAttackDescriptionTextField); m_specialCharacterAttackDescriptionTextField.visible = false; var i:int; while (i < m_turltePortraits.length) { portraitClass = m_turltePortraits[i]; portrait = new Sprite(); portrait.addChild(new (portraitClass)); portrait.buttonMode = true; portrait.name = m_turtleNames[i]; portrait.x = (75 * i); portrait.filters = [new DropShadowFilter()]; portrait.addEventListener(MouseEvent.CLICK, click, false, 0, true); portrait.addEventListener(MouseEvent.MOUSE_OVER, movedOverPortrait); portrait.addEventListener(MouseEvent.MOUSE_OUT, movedOutOfPortrait); portrait.name = m_turtleNames[i]; m_characterPortraitContainer.addChild(portrait); i++; }; m_characterPortraitContainer.x = ((Constants.RENDER_WIDTH / 2) - (m_characterPortraitContainer.width / 2)); m_characterPortraitContainer.y = ((Constants.RENDER_HEIGHT / 2) - (m_characterPortraitContainer.height / 2)); m_charactSelectTitleTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_charactSelectTitleTextField.width / 2)); m_charactSelectTitleTextField.y = ((m_characterPortraitContainer.y - m_charactSelectTitleTextField.height) - s_potraitContainerMargin); var backButton:VistaButton = TMNTButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.y = (Constants.RENDER_HEIGHT - backButton.height); m_uiContainer.addChild(backButton); showCharacterName(""); showCharacterAttackDescription(""); showCharacterSpecialAttackDescription(""); } public function get selectedTurtle():String{ return (m_selectedTurtle); } } }//package game.ui
Section 222
//ComboContainer (game.ui.ComboContainer) package game.ui { import flash.display.*; import shared.*; import flash.filters.*; public class ComboContainer extends Sprite { private var m_comboTextfield:DefaultTextField; private var m_label:DefaultTextField; public function ComboContainer(){ super(); m_label = new DefaultTextField(); m_label.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; addChild(m_label); m_label.text = "COMBO"; m_comboTextfield = new DefaultTextField("", 0xFFFFFF, 48); m_comboTextfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; addChild(m_comboTextfield); m_comboTextfield.y = (m_label.height - 8); m_comboTextfield; } public function updateCombo(a_combo:int):void{ m_comboTextfield.text = (a_combo + ""); m_comboTextfield.x = ((m_label.width / 2) - (m_comboTextfield.width / 2)); } } }//package game.ui
Section 223
//CreditsScreen (game.ui.CreditsScreen) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; import com.urbansquall.ui.*; import flash.net.*; import flash.filters.*; public class CreditsScreen extends Sprite { private var m_drawIndex:int;// = 0 private var m_spaceBetweenEntries:Number;// = 42 private var m_drawHeight:Number;// = 95 public function CreditsScreen(){ var textfield:DefaultTextField; super(); var bg:DisplayObject = new AssetLibrary.STREET_STATIC_BG(); addChild(bg); var bgoverlay:Sprite = new Sprite(); bgoverlay.graphics.beginFill(0, 0.7); bgoverlay.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); bgoverlay.y = (bgoverlay.y + (m_drawHeight - 48)); addChild(bgoverlay); var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField("CREDITS", textColor, 26); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.x = ((Constants.RENDER_WIDTH / 2) - (textfield.width / 2)); textfield.y = 5; textfield.center(); addChild(textfield); var urbansquallButton:Sprite = new Sprite(); urbansquallButton.addChild(new AssetLibrary.URBANSQUALL_BUTTON()); urbansquallButton.filters = [new DropShadowFilter()]; urbansquallButton.addEventListener(MouseEvent.CLICK, clickUrbansquall, false, 0, true); addChild(urbansquallButton); urbansquallButton.x = ((Constants.RENDER_WIDTH / 2) - (urbansquallButton.width / 2)); urbansquallButton.y = (Constants.RENDER_HEIGHT - 30); urbansquallButton.buttonMode = true; urbansquallButton.addEventListener(MouseEvent.ROLL_OVER, rollover, false, 0, true); urbansquallButton.addEventListener(MouseEvent.ROLL_OUT, rollout, false, 0, true); createLine("falling", "Art: T. Wendorf, R. Janes", "raphael"); createLine("combo1", "Writing: M. Scarpelli", "leonardo"); createLine("combo2", "Illustrations: K. Kho", "michelangelo"); createLine("combo3", "Design: A. Pellerano", "donatello"); createLine("run", "Music & SFX: J. Whelchel", "hun"); createLine("idle", "Programming: J. Konik, P. Haritatos, A. Pellerano, D. Miles", "special_splinter"); var backButton:VistaButton = TMNTButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.y = (Constants.RENDER_HEIGHT - backButton.height); addChild(backButton); } private function rollover(a_event:Event):void{ var target:DisplayObject = (a_event.currentTarget as DisplayObject); target.filters = [new GlowFilter(0xFFFFFF)]; } private function createGinger(a_animationID:String, a_ginger:String):AnimationPlayer{ var ginger:AnimationPlayer = GingerFactory.getInstance().instantiate(a_ginger); ginger.addEventListener(AnimationEvent.CHANGE, forceLoop); ginger.startSelfTick(50); ginger.play(a_animationID); addChild(ginger); return (ginger); } private function forceLoop(a_animationEvent:AnimationEvent):void{ var ginger:AnimationPlayer; if (!a_animationEvent.begin){ ginger = (a_animationEvent.currentTarget as AnimationPlayer); ginger.play(a_animationEvent.animationID); }; } private function createLine(a_animationID:String, a_description:String, a_ginger:String="leonardo"):void{ var textfield:DefaultTextField; var offsetX:Number = 10; var textColor:uint = 0xFFFFFF; var rightMargin = 455; textfield = new DefaultTextField(a_description, textColor, 16); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "none"; textfield.wordWrap = true; textfield.multiline = true; textfield.width = rightMargin; textfield.x = (90 + offsetX); textfield.y = (m_drawHeight - 10); addChild(textfield); var ginger:AnimationPlayer = createGinger(a_animationID, a_ginger); ginger.x = (46 + offsetX); ginger.y = m_drawHeight; if ((m_drawIndex % 2) == 1){ textfield.right(); ginger.x = (ginger.x + (rightMargin + 86)); }; m_drawHeight = (m_drawHeight + m_spaceBetweenEntries); m_drawIndex++; } private function rollout(a_event:Event):void{ var target:DisplayObject = (a_event.currentTarget as DisplayObject); target.filters = []; } private function clickUrbansquall(a_event:Event):void{ navigateToURL(new URLRequest("http://www.urbansquall.com"), "_new"); } public function clickBack(a_event:Event):void{ dispatchEvent(new Event(Event.COMPLETE)); } } }//package game.ui
Section 224
//GameEndScreen (game.ui.GameEndScreen) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.text.*; import com.urbansquall.ui.*; import flash.net.*; import flash.filters.*; public class GameEndScreen extends Sprite { private var m_container:Sprite; public function GameEndScreen(a_score:int, a_victory:Boolean, a_levelNum:int){ super(); m_container = new Sprite(); var packArt:Sprite = new Sprite(); packArt.addChild(new AssetLibrary.PACKSHOT_LARGE()); packArt.x = 10; packArt.y = 40; if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ packArt.addEventListener(MouseEvent.MOUSE_OVER, glow); packArt.addEventListener(MouseEvent.MOUSE_OUT, unglow); packArt.addEventListener(MouseEvent.CLICK, packArtClick); packArt.buttonMode = true; }; m_container.addChild(packArt); var headerText:String = ""; if (a_victory){ headerText = (("Level " + a_levelNum.toString()) + " Completed!"); } else { headerText = "You Lost!"; }; var results:TextField = createTextField(headerText, 24); m_container.addChild(results); var closeButtonText:String = "Continue"; if (!a_victory){ closeButtonText = "Exit"; }; var buttonHeight = 80; var buttonWidth = 160; var tryAgainButton:VistaButton = TMNTButtonFactory.instance.createButton("Try Again"); tryAgainButton.addEventListener(MouseEvent.CLICK, clickTryAgain); tryAgainButton.x = 210; tryAgainButton.y = results.y; tryAgainButton.width = buttonWidth; tryAgainButton.height = buttonHeight; m_container.addChild(tryAgainButton); var changeCharacters:VistaButton = TMNTButtonFactory.instance.createButton("Change Characters"); changeCharacters.width = buttonWidth; changeCharacters.height = buttonHeight; changeCharacters.addEventListener(MouseEvent.CLICK, clickChangeCharacters); changeCharacters.x = tryAgainButton.x; changeCharacters.y = ((tryAgainButton.y + tryAgainButton.height) + 18); m_container.addChild(changeCharacters); var closeButton:VistaButton = TMNTButtonFactory.instance.createButton(closeButtonText); closeButton.addEventListener(MouseEvent.CLICK, clickClose); closeButton.x = changeCharacters.x; closeButton.y = ((changeCharacters.y + changeCharacters.height) + 18); closeButton.width = buttonWidth; closeButton.height = buttonHeight; m_container.addChild(closeButton); if (a_victory){ changeCharacters.visible = false; tryAgainButton.visible = false; }; var popUp:Popup = new Popup(m_container, 60, 60); addChild(popUp); } private function clickClose(a_event:Event):void{ this.dispatchEvent(new Event(Event.CLOSE)); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 250; }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.width = a_width; addChild(textfield); return (textfield); } private function clickChangeCharacters(a_event:Event):void{ this.dispatchEvent(new Event(Event.CHANGE)); } private function clickTryAgain(a_event:Event):void{ this.dispatchEvent(new Event(Event.OPEN)); } private function unglow(a_event:Event):void{ a_event.target.filters = []; } public function makeVisible(a_event:Event=null):void{ this.visible = true; } private function glow(a_event:Event):void{ a_event.target.filters = [new GlowFilter(0xFFFFFF, 1, 6, 6, 5)]; } private function packArtClick(a_event:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_BUY_NOW_LINK); navigateToURL(target, "_blank"); } } }//package game.ui
Section 225
//HelpScreen (game.ui.HelpScreen) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; import com.urbansquall.ui.*; import flash.net.*; import flash.filters.*; public class HelpScreen extends Sprite { private var m_spaceBetweenEntries:Number;// = 42 private var m_drawIndex:int;// = 0 private var m_drawHeight:Number;// = 95 public function HelpScreen(){ var textfield:DefaultTextField; super(); var bg:DisplayObject = new AssetLibrary.STREET_STATIC_BG(); addChild(bg); var bgoverlay:Sprite = new Sprite(); bgoverlay.graphics.beginFill(0, 0.7); bgoverlay.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); bgoverlay.y = (bgoverlay.y + (m_drawHeight - 48)); addChild(bgoverlay); var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField("HELP", textColor, 26); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.x = ((Constants.RENDER_WIDTH / 2) - (textfield.width / 2)); textfield.y = 5; textfield.center(); addChild(textfield); createLine("walk", "Press LEFT or RIGHT to move."); createLine("combo1", "Press A to attack."); createLine("jumping", "Press UP to jump."); createLine("airattack", "Press A in the air to air attack."); createLine("combo2", "Experiment to create combos."); createLine("special", "Press S to use special attack."); createLine("idle", "Pizza gives you health.", "pizza_slice"); createLine("idle", "Ooze drops power special attacks.", "ooze_drop"); var backButton:VistaButton = TMNTButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.y = (Constants.RENDER_HEIGHT - backButton.height); addChild(backButton); } private function createLine(a_animationID:String, a_description:String, a_ginger:String="leonardo"):void{ var textfield:DefaultTextField; var offsetX:Number = 10; var textColor:uint = 0xFFFFFF; var rightMargin = 445; textfield = new DefaultTextField(a_description, textColor, 16); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "none"; textfield.wordWrap = true; textfield.multiline = true; textfield.width = rightMargin; textfield.x = (90 + offsetX); textfield.y = (m_drawHeight - 10); addChild(textfield); var ginger:AnimationPlayer = createGinger(a_animationID, a_ginger); ginger.x = (46 + offsetX); ginger.y = m_drawHeight; if ((m_drawIndex % 2) == 1){ textfield.right(); ginger.x = (ginger.x + (rightMargin + 86)); }; m_drawHeight = (m_drawHeight + m_spaceBetweenEntries); m_drawIndex++; } private function createGinger(a_animationID:String, a_ginger:String):AnimationPlayer{ var ginger:AnimationPlayer = GingerFactory.getInstance().instantiate(a_ginger); ginger.addEventListener(AnimationEvent.CHANGE, forceLoop); ginger.startSelfTick(50); ginger.play(a_animationID); addChild(ginger); return (ginger); } private function forceLoop(a_animationEvent:AnimationEvent):void{ var ginger:AnimationPlayer; if (!a_animationEvent.begin){ ginger = (a_animationEvent.currentTarget as AnimationPlayer); if (a_animationEvent.animationID == "combo2"){ ginger.play("crouchattack"); } else { if (a_animationEvent.animationID == "crouchattack"){ ginger.play("combo2"); } else { ginger.play(a_animationEvent.animationID); }; }; }; } private function clickUrbansquall(a_event:Event):void{ navigateToURL(new URLRequest("http://www.urbansquall.com"), "_new"); } public function clickBack(a_event:Event):void{ dispatchEvent(new Event(Event.COMPLETE)); } } }//package game.ui
Section 226
//InActiveStatusBox (game.ui.InActiveStatusBox) package game.ui { import flash.display.*; import shared.*; public class InActiveStatusBox extends Sprite { private var s_oozeBarContainerWidth:Number;// = 13 private var m_activationLine:Sprite;// = null private var m_specialAttackOozeUsage:int;// = 9 private var m_maxBarHeight:Number;// = 0 private var s_oozeBarMargin:Number;// = 2 private var m_oozeBarContainer:Sprite;// = null private var m_bar:Sprite;// = null private var m_oozeBarToOozeRaitio:Number;// = 0 private var m_ooze:int;// = 0 public function InActiveStatusBox(a_width:Number, a_height:Number, a_oozeCost:int){ super(); m_specialAttackOozeUsage = a_oozeCost; m_maxBarHeight = (a_height - 3); m_oozeBarToOozeRaitio = (m_maxBarHeight / Constants.STARTING_CHARGE); m_oozeBarContainer = new Sprite(); m_oozeBarContainer.graphics.lineStyle(1, 0xFFFFFF); m_oozeBarContainer.graphics.beginFill(0); m_oozeBarContainer.graphics.drawRect(0, 0, s_oozeBarContainerWidth, a_height); m_oozeBarContainer.graphics.endFill(); addChild(m_oozeBarContainer); var barHeight:Number = (m_specialAttackOozeUsage * m_oozeBarToOozeRaitio); m_activationLine = new Sprite(); m_activationLine.graphics.lineStyle(1, 0xFFFFFF); m_activationLine.graphics.moveTo(0, 0); m_activationLine.graphics.lineTo(s_oozeBarContainerWidth, 0); m_activationLine.x = 0; m_activationLine.y = ((m_maxBarHeight - barHeight) + s_oozeBarMargin); m_oozeBarContainer.addChild(m_activationLine); setOoze(m_ooze); } public function setOoze(a_ooze:int):void{ m_ooze = a_ooze; if (m_bar != null){ m_oozeBarContainer.removeChild(m_bar); m_oozeBarContainer.removeChild(m_activationLine); m_bar = null; }; drawOoze(); m_oozeBarContainer.addChild(m_activationLine); } private function drawOoze():void{ var barHeight:Number = (m_ooze * m_oozeBarToOozeRaitio); m_bar = new Sprite(); m_bar.graphics.beginFill(0xFF00, 1); m_bar.graphics.drawRect(0, 0, ((s_oozeBarContainerWidth - (s_oozeBarMargin * 2)) + 1), barHeight); m_bar.graphics.endFill(); m_bar.x = s_oozeBarMargin; m_bar.y = ((m_maxBarHeight - barHeight) + s_oozeBarMargin); m_oozeBarContainer.addChild(m_bar); } } }//package game.ui
Section 227
//InGameOptions (game.ui.InGameOptions) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import com.urbansquall.audio.*; import com.urbansquall.ui.*; import game.*; public class InGameOptions extends Sprite { private var m_separationX:Number;// = 120 private var m_prevSoundVolume:Number;// = 0 private var m_closeKeyPressed:Boolean;// = false private var m_game:Game;// = null private var m_muteMusicButton:VistaButton;// = null private var m_restartLevelButton:VistaButton;// = null private var m_prevMusicVolume:Number;// = 0 private var m_popupWidth:Number; private var m_buttonWidth:Number;// = 200 private var m_closeKeyCode:uint;// = 0 private var m_muteSoundButton:VistaButton;// = null private static const s_unmuteMusicText:String = "Unmute Music"; private static const s_muteSoundText:String = "Mute Sound"; private static const s_buttonMargin:Number = 10; private static const s_muteMusicText:String = "Mute Music"; private static const s_unmuteSoundText:String = "Unmute Sound"; public function InGameOptions(a_game:Game, a_closeKeyCode:uint){ m_popupWidth = m_buttonWidth; super(); var muteSoundButtonText:String = calculateSoundButtonText(); var muteMusicButtonText:String = calculateMusicButtonText(); m_game = a_game; m_closeKeyCode = a_closeKeyCode; m_prevSoundVolume = SoundSystem.instance.getMasterEffectVolume(); m_prevMusicVolume = SoundSystem.instance.getMasterLoopVolume(); if (m_prevSoundVolume == 0){ m_prevSoundVolume = 0.5; }; if (m_prevMusicVolume == 0){ (m_prevMusicVolume == 0.5); }; var returnToGameButton:VistaButton = TMNTButtonFactory.instance.createButton("Return To Game"); initializeButton(null, returnToGameButton, m_popupWidth, clickClose, m_buttonWidth); addChild(returnToGameButton); m_restartLevelButton = TMNTButtonFactory.instance.createButton("Restart Level"); initializeButton(returnToGameButton, m_restartLevelButton, m_popupWidth, clickRestartLevel, m_buttonWidth); addChild(m_restartLevelButton); m_muteSoundButton = TMNTButtonFactory.instance.createButton(muteSoundButtonText); initializeButton(m_restartLevelButton, m_muteSoundButton, m_popupWidth, clickMuteUnMuteSound, m_buttonWidth); addChild(m_muteSoundButton); m_muteMusicButton = TMNTButtonFactory.instance.createButton(muteMusicButtonText); initializeButton(m_muteSoundButton, m_muteMusicButton, m_popupWidth, clickMuteUnMuteMusic, m_buttonWidth); addChild(m_muteMusicButton); var exitGameButton:VistaButton = TMNTButtonFactory.instance.createButton("Exit Level"); initializeButton(m_muteMusicButton, exitGameButton, m_popupWidth, clickExitGame, m_buttonWidth); addChild(exitGameButton); addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, false); addEventListener(KeyboardEvent.KEY_UP, onKeyUp, false, 0, false); addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } private function onKeyDown(e:KeyboardEvent):void{ if (e.keyCode == m_closeKeyCode){ m_closeKeyPressed = true; }; } private function clickClose(a_event:Event):void{ close(); } private function clickRestartLevel(a_event:Event):void{ close(); m_game.restartLevel(); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = (m_separationX - 10); }; var textColor:uint; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.autoSize = "none"; textfield.wordWrap = true; textfield.multiline = true; textfield.center(); textfield.width = a_width; addChild(textfield); return (textfield); } private function clickMuteUnMuteSound(a_event:Event):void{ if (SoundSystem.instance.getMasterEffectVolume() > 0){ SoundSystem.instance.setMasterEffectVolume(0); } else { SoundSystem.instance.setMasterEffectVolume(m_prevSoundVolume); }; var muteSoundButtonText:String = calculateSoundButtonText(); removeChild(m_muteSoundButton); m_muteSoundButton = null; m_muteSoundButton = TMNTButtonFactory.instance.createButton(muteSoundButtonText); initializeButton(m_restartLevelButton, m_muteSoundButton, m_popupWidth, clickMuteUnMuteSound, m_buttonWidth); addChild(m_muteSoundButton); } private function clickExitGame(a_event:Event):void{ close(); m_game.close(); } private function calculateSoundButtonText():String{ if (SoundSystem.instance.getMasterEffectVolume() == 0){ return (s_unmuteSoundText); }; return (s_muteSoundText); } private function onAddedToStage(e:Event):void{ removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); this.stage.focus = this; } private function initializeButton(prevButton:DisplayObject, curButton:DisplayObject, containerWidth:Number, clickHandler:Function, buttonWidth:Number):void{ curButton.width = buttonWidth; if (prevButton == null){ curButton.y = 0; } else { curButton.y = ((prevButton.y + prevButton.height) + s_buttonMargin); }; curButton.x = ((containerWidth / 2) - (curButton.width / 2)); curButton.addEventListener(MouseEvent.CLICK, clickHandler); } public function close():void{ this.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp, false); this.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false); this.stage.focus = null; dispatchEvent(new Event(Event.CLOSE)); } private function clickMuteUnMuteMusic(a_event:Event):void{ if (SoundSystem.instance.getMasterLoopVolume() > 0){ SoundSystem.instance.setMasterLoopVolume(0); } else { SoundSystem.instance.setMasterLoopVolume(m_prevMusicVolume); }; var muteMusicButtonText:String = calculateMusicButtonText(); removeChild(m_muteMusicButton); m_muteMusicButton = null; m_muteMusicButton = TMNTButtonFactory.instance.createButton(muteMusicButtonText); initializeButton(m_muteSoundButton, m_muteMusicButton, m_popupWidth, clickMuteUnMuteMusic, m_buttonWidth); addChild(m_muteMusicButton); } private function onKeyUp(e:KeyboardEvent):void{ if ((((e.keyCode == m_closeKeyCode)) && (m_closeKeyPressed))){ close(); }; } private function calculateMusicButtonText():String{ if (SoundSystem.instance.getMasterLoopVolume() == 0){ return (s_unmuteMusicText); }; return (s_muteMusicText); } } }//package game.ui
Section 228
//MuteButton (game.ui.MuteButton) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import com.urbansquall.prophet.display.*; import com.urbansquall.audio.*; import flash.utils.*; import flash.filters.*; public class MuteButton extends Sprite { private var m_timer:Timer; private var m_ginger:AnimationPlayer; public function MuteButton(){ super(); m_ginger = GingerFactory.getInstance().instantiate("mute_button"); addChild(m_ginger); this.buttonMode = true; this.addEventListener(MouseEvent.CLICK, toggleMute); this.addEventListener(MouseEvent.ROLL_OUT, onRollout); this.addEventListener(MouseEvent.ROLL_OVER, onRollover); } public function onRollover(a_event:Event):void{ this.filters = [new GlowFilter()]; } private function showUnmuted():void{ m_ginger.play("unmuted"); } public function update(a_timerEvent:TimerEvent):void{ if (SoundSystem.instance.isMuted()){ showMuted(); } else { showUnmuted(); }; } public function onRollout(a_event:Event):void{ this.filters = []; } private function toggleMute(a_event:Event):void{ SoundSystem.instance.toggleMute(); update(null); } private function showMuted():void{ m_ginger.play("muted"); } } }//package game.ui
Section 229
//Popup (game.ui.Popup) package game.ui { import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.display.*; public class Popup extends Sprite { private static var s_panelTile9Data:Tile9Data = null; public function Popup(a_contents:DisplayObject, a_padWidth:int=40, a_padHeight:int=40){ var panelData:DisplayObject; var tile9Rect:Rectangle; super(); var background:Sprite = new Sprite(); background.graphics.beginFill(0, 0.5); background.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); addChild(background); if (s_panelTile9Data == null){ panelData = new AssetLibrary.PANEL(); tile9Rect = new Rectangle(12, 12, 22, 22); s_panelTile9Data = new Tile9Data(panelData, tile9Rect); }; var tile9:Tile9 = new Tile9(s_panelTile9Data); var popupWidth:int = int((a_contents.width + a_padWidth)); var popupHeight:int = int((a_contents.height + a_padHeight)); tile9.width = popupWidth; tile9.height = popupHeight; addChild(tile9); tile9.x = int(((Constants.RENDER_WIDTH / 2) - (popupWidth / 2))); tile9.y = int(((Constants.RENDER_HEIGHT / 2) - (popupHeight / 2))); a_contents.x = int(((Constants.RENDER_WIDTH / 2) - (a_contents.width / 2))); a_contents.y = int(((Constants.RENDER_HEIGHT / 2) - (a_contents.height / 2))); addChild(a_contents); } } }//package game.ui
Section 230
//PreLevelInfo (game.ui.PreLevelInfo) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import flash.filters.*; public class PreLevelInfo extends Sprite { private var m_separationX:Number;// = 120 private var m_gingers:Array; public function PreLevelInfo(a_scoreToBeat:int){ var textfield:DefaultTextField; var image:DisplayObject; var ginger:AnimationPlayer; m_gingers = []; super(); var imageOffsetY:Number = 95; var labelY:Number = 0; textfield = createTextField("Press any key to begin! ", 24, 300); textfield.x = ((this.width / 2) - (textfield.width / 2)); textfield.y = 0; textfield.height = 60; this.addEventListener(Event.ENTER_FRAME, tick, false, 0, true); this.addEventListener(MouseEvent.CLICK, close, false, 0, true); this.addEventListener(KeyboardEvent.KEY_UP, close, false, 0, true); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = (m_separationX - 10); }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "none"; textfield.wordWrap = true; textfield.multiline = true; textfield.center(); textfield.width = a_width; addChild(textfield); return (textfield); } private function close(a_event:Event):void{ this.removeEventListener(MouseEvent.CLICK, close, false); this.removeEventListener(KeyboardEvent.KEY_UP, close, false); this.removeEventListener(Event.ENTER_FRAME, tick, false); m_gingers.splice(0); dispatchEvent(new Event(Event.COMPLETE)); } private function tick(a_event:Event):void{ var ginger:AnimationPlayer; this.stage.focus = this; var i:int; while (i < m_gingers.length) { ginger = m_gingers[i]; ginger.update(10); i++; }; } } }//package game.ui
Section 231
//RegularInputHelp (game.ui.RegularInputHelp) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.engine.*; import flash.text.*; import com.urbansquall.ui.*; import flash.filters.*; public class RegularInputHelp extends Sprite { private var m_container:Sprite; public function RegularInputHelp(){ super(); m_container = new Sprite(); var results:TextField = createTextField("Controls", 24); results.textColor = 0xFFFFFF; results.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; m_container.addChild(results); var helpImage:DisplayObject = new AssetLibrary.INPUT_HELP(); helpImage.x = ((results.width / 2) - (helpImage.width / 2)); helpImage.y = 55; m_container.addChild(helpImage); var buttonWidth:Number = 150; var closeButton:VistaButton = TMNTButtonFactory.instance.createButton("Hide Forever"); closeButton.width = buttonWidth; closeButton.addEventListener(MouseEvent.CLICK, clickCloseForever); closeButton.x = int((((results.width / 2) - (closeButton.width / 2)) - 85)); closeButton.y = int((m_container.height + 15)); m_container.addChild(closeButton); var closeForeverButton:VistaButton = TMNTButtonFactory.instance.createButton("Continue"); closeForeverButton.width = buttonWidth; closeForeverButton.addEventListener(MouseEvent.CLICK, clickClose); closeForeverButton.x = int((((results.width / 2) - (closeButton.width / 2)) + 85)); closeForeverButton.y = int(closeButton.y); m_container.addChild(closeForeverButton); var popUp:Popup = new Popup(m_container, 110, 80); addChild(popUp); } private function clickClose(a_event:Event):void{ this.dispatchEvent(new Event(Event.CLOSE)); } private function clickCloseForever(a_event:Event):void{ SafeSol.instance.writeBool("hide_input", true); this.dispatchEvent(new Event(Event.CLOSE)); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 330; }; var textColor:uint; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.center(); textfield.width = a_width; addChild(textfield); return (textfield); } } }//package game.ui
Section 232
//SecondaryCharacterSelectScreen (game.ui.SecondaryCharacterSelectScreen) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.geom.*; import flash.text.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.ui.levelscreen.*; import com.urbansquall.display.*; import flash.utils.*; import game.*; import flash.net.*; import flash.filters.*; import flash.external.*; public class SecondaryCharacterSelectScreen extends Sprite { private var m_portraitClasses:Array; private var m_attackDescriptionsDict:Dictionary; private var m_specialCharacterAttackDescriptionTextField:DefaultTextField;// = null private var m_characterPortraitContainer:DisplayObjectContainer;// = null private var m_charactSelectTitleTextField:DefaultTextField;// = null private var m_primaryCharacter:String; private var m_secondaryCharacterNames:Array; private var m_selectedSecondaryCharacter:String; private var m_characterNameTextField:DefaultTextField;// = null private var m_specialCharactersUnlocked:Boolean;// = false private var m_uiContainer:Sprite;// = null private var m_specialAttackDescriptionsDict:Dictionary; private static const s_potraitContainerMargin:Number = 10; private static const s_selectSecondaryCharacterText:String = "Select Your Special Attack Partner"; private static const s_fontSize:int = 18; public function SecondaryCharacterSelectScreen(a_primaryCharacter:String, a_secondaryCharacter:String){ m_attackDescriptionsDict = new Dictionary(); m_specialAttackDescriptionsDict = new Dictionary(); super(); m_primaryCharacter = a_primaryCharacter; m_selectedSecondaryCharacter = a_secondaryCharacter; if (Constants.ALLOW_DEBUG){ }; m_portraitClasses = [AssetLibrary.PORTRAIT_LEONARDO, AssetLibrary.PORTRAIT_RAPHAEL, AssetLibrary.PORTRAIT_DONATELLO, AssetLibrary.PORTRAIT_MICHELANGELO, AssetLibrary.PORTRAIT_PIZZA_DUDE, AssetLibrary.PORTRAIT_SPLINTER, AssetLibrary.PORTRAIT_CASEY_JONES]; m_secondaryCharacterNames = [Constants.CHARACTER_LEONARDO, Constants.CHARACTER_RAPHAEL, Constants.CHARACTER_DONATELLO, Constants.CHARACTER_MICHELANGELO, Constants.CHARACTER_PIZZA_DUDE, Constants.CHARACTER_SPLINTER, Constants.CHARACTER_CASEY_JONES]; m_attackDescriptionsDict[Constants.CHARACTER_LEONARDO] = Constants.CHARACTER_ATTACK_DESCRIPTION_LEONARDO; m_attackDescriptionsDict[Constants.CHARACTER_RAPHAEL] = Constants.CHARACTER_ATTACK_DESCRIPTION_RAPHAEL; m_attackDescriptionsDict[Constants.CHARACTER_DONATELLO] = Constants.CHARACTER_ATTACK_DESCRIPTION_DONATELLO; m_attackDescriptionsDict[Constants.CHARACTER_MICHELANGELO] = Constants.CHARACTER_ATTACK_DESCRIPTION_MICHELANGELO; m_specialAttackDescriptionsDict[Constants.CHARACTER_LEONARDO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_LEONARDO; m_specialAttackDescriptionsDict[Constants.CHARACTER_RAPHAEL] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_RAPHAEL; m_specialAttackDescriptionsDict[Constants.CHARACTER_DONATELLO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_DONATELLO; m_specialAttackDescriptionsDict[Constants.CHARACTER_MICHELANGELO] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_MICHELANGELO; m_specialAttackDescriptionsDict[Constants.CHARACTER_SPLINTER] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_SPLINTER; m_specialAttackDescriptionsDict[Constants.CHARACTER_CASEY_JONES] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_CASEY_JONES; m_specialAttackDescriptionsDict[Constants.CHARACTER_PIZZA_DUDE] = Constants.CHARACTER_SPECIAL_ATTACK_DESCRIPTION_PIZZA_DUDE; this.addEventListener(Event.ADDED_TO_STAGE, addedToStage); } private function click(a_e:Event):void{ var lockedTextContainer:Sprite; var lockedText:TextField; var lockedTextMessage:String; var popup:Popup; var button:VistaButton; if (((!(m_specialCharactersUnlocked)) && ((((a_e.currentTarget.name == Constants.CHARACTER_SPLINTER)) || ((a_e.currentTarget.name == Constants.CHARACTER_CASEY_JONES)))))){ lockedTextContainer = new Sprite(); lockedText = new TextField(); lockedTextMessage = "Play on tmntgame.com for access to the bonus characters!"; lockedText = createTextField(lockedTextMessage); lockedText.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; lockedTextContainer.addChild(lockedText); if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ button = TMNTButtonFactory.instance.createButton("Open tmntgame.com"); button.width = 300; button.height = 100; lockedTextContainer.addChild(button); button.x = int(50); button.y = int((lockedText.height + 5)); button.addEventListener(MouseEvent.CLICK, clickLink); }; popup = new Popup(lockedTextContainer, 40, 90); popup.addEventListener(MouseEvent.CLICK, killPopup); addChild(popup); return; }; m_selectedSecondaryCharacter = a_e.currentTarget.name; this.dispatchEvent(new Event(Event.COMPLETE)); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 400; }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.center(); textfield.width = a_width; addChild(textfield); return (textfield); } private function movedOutOfPortrait(a_event:MouseEvent):void{ var portrait:DisplayObject = (a_event.target as DisplayObject); showCharacterName(""); showCharacterSpecialAttackDescription(""); portrait.filters = [new DropShadowFilter()]; } private function clickBack(a_event:Event):void{ this.dispatchEvent(new Event(Event.CANCEL)); } private function showCharacterName(a_characterName:String):void{ m_characterNameTextField.text = a_characterName; m_characterNameTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_characterNameTextField.width / 2)); m_characterNameTextField.y = ((m_characterPortraitContainer.y + m_characterPortraitContainer.height) + s_potraitContainerMargin); } public function get secondaryCharacter():String{ return (m_selectedSecondaryCharacter); } private function addedToStage(a_event:Event):void{ var url:String; this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage); if (ExternalInterface.available){ url = this.root.loaderInfo.url; if ((((((url.indexOf(".ubi.com") > -1)) || ((url.indexOf(".kongregate.com") > -1)))) || ((url.indexOf(".ungrounded.net") > -1)))){ m_specialCharactersUnlocked = true; }; }; if (Constants.UNLOCK_ALL){ m_specialCharactersUnlocked = true; }; redraw(); } private function showCharacterSpecialAttackDescription(a_specialAttackDescription:String):void{ m_specialCharacterAttackDescriptionTextField.text = a_specialAttackDescription; m_specialCharacterAttackDescriptionTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_specialCharacterAttackDescriptionTextField.width / 2)); m_specialCharacterAttackDescriptionTextField.y = ((m_characterNameTextField.y + m_characterNameTextField.height) + s_potraitContainerMargin); } private function clickLink(a_event:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_SITE_LINK); navigateToURL(target, "_blank"); } private function killPopup(a_event:Event):void{ var popup:Popup = (a_event.currentTarget as Popup); popup.parent.removeChild(popup); } private function movedOverPortrait(a_event:MouseEvent):void{ var portrait:DisplayObject = (a_event.target as DisplayObject); portrait.filters = [new GlowFilter(0xFFFFFF), new DropShadowFilter()]; showCharacterName(portrait.name); showCharacterSpecialAttackDescription(m_specialAttackDescriptionsDict[portrait.name]); } private function redraw():void{ var portraitClass:Class; var portrait:Sprite; var lock:Bitmap; if (m_uiContainer != null){ removeChild(m_uiContainer); }; m_uiContainer = new Sprite(); addChild(m_uiContainer); var panelData:DisplayObject = new AssetLibrary.PANEL(); var tile9Rect:Rectangle = new Rectangle(12, 12, 22, 22); var tile9Data:Tile9Data = new Tile9Data(panelData, tile9Rect); var tile9:Tile9 = new Tile9(tile9Data); var bgWidth:Number = 600; var bgHeight:Number = 215; tile9.width = bgWidth; tile9.height = bgHeight; tile9.x = ((Constants.RENDER_WIDTH / 2) - (bgWidth / 2)); tile9.y = ((Constants.RENDER_HEIGHT / 2) - (150 / 2)); m_uiContainer.addChild(tile9); m_characterPortraitContainer = new Sprite(); m_uiContainer.addChild(m_characterPortraitContainer); m_charactSelectTitleTextField = createTextField(s_selectSecondaryCharacterText, (s_fontSize + 2)); m_uiContainer.addChild(m_charactSelectTitleTextField); m_characterNameTextField = createTextField("", s_fontSize); m_uiContainer.addChild(m_characterNameTextField); m_specialCharacterAttackDescriptionTextField = createTextField("", s_fontSize); m_uiContainer.addChild(m_specialCharacterAttackDescriptionTextField); var i:int; while (i < m_portraitClasses.length) { portraitClass = m_portraitClasses[i]; portrait = new Sprite(); portrait.addChild(new (portraitClass)); portrait.name = m_secondaryCharacterNames[i]; if (portrait.name == m_primaryCharacter){ portrait.alpha = 0.5; } else { portrait.buttonMode = true; portrait.addEventListener(MouseEvent.CLICK, click, false, 0, true); portrait.addEventListener(MouseEvent.MOUSE_OVER, movedOverPortrait); portrait.addEventListener(MouseEvent.MOUSE_OUT, movedOutOfPortrait); }; portrait.filters = [new DropShadowFilter()]; if (((!(m_specialCharactersUnlocked)) && ((((portrait.name == Constants.CHARACTER_SPLINTER)) || ((portrait.name == Constants.CHARACTER_CASEY_JONES)))))){ lock = new AssetLibrary.LEVEL_LOCK(); portrait.addChild(lock); }; portrait.x = (75 * i); portrait.name = m_secondaryCharacterNames[i]; m_characterPortraitContainer.addChild(portrait); i++; }; m_characterPortraitContainer.x = ((Constants.RENDER_WIDTH / 2) - (m_characterPortraitContainer.width / 2)); m_characterPortraitContainer.y = ((Constants.RENDER_HEIGHT / 2) - (m_characterPortraitContainer.height / 2)); m_charactSelectTitleTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_charactSelectTitleTextField.width / 2)); m_charactSelectTitleTextField.y = ((m_characterPortraitContainer.y - m_charactSelectTitleTextField.height) - s_potraitContainerMargin); m_characterNameTextField.x = ((Constants.RENDER_WIDTH / 2) - (m_characterNameTextField.width / 2)); m_characterNameTextField.y = ((m_characterPortraitContainer.y + m_characterPortraitContainer.height) + s_potraitContainerMargin); var backButton:VistaButton = TMNTButtonFactory.instance.createButton("Back"); backButton.addEventListener(MouseEvent.CLICK, clickBack); backButton.y = (Constants.RENDER_HEIGHT - backButton.height); m_uiContainer.addChild(backButton); showCharacterName(""); showCharacterSpecialAttackDescription(""); } } }//package game.ui
Section 233
//SpeechBubble (game.ui.SpeechBubble) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.display.*; public class SpeechBubble extends Sprite { private var m_speechBubble:Tile9; private var m_textfield:DefaultTextField; private var m_container:Sprite; private static var s_speechBubbleData:Tile9Data = null; public function SpeechBubble(a_speech:String){ var bgData:DisplayObject; var rect:Rectangle; super(); if (s_speechBubbleData == null){ bgData = new AssetLibrary.SIGN_BUBBLE(); rect = new Rectangle(16, 16, (bgData.width - (2 * 16)), (bgData.height - (2 * 16))); s_speechBubbleData = new Tile9Data(bgData, rect); }; m_container = new Sprite(); addChild(m_container); m_speechBubble = new Tile9(s_speechBubbleData); m_speechBubble.height = 50; m_container.addChild(m_speechBubble); var regExp:RegExp = new RegExp("~n", "g"); var processedSpeech:String = a_speech.replace(regExp, "\n"); regExp = new RegExp("~t", "g"); processedSpeech = processedSpeech.replace(regExp, "\t"); m_textfield = new DefaultTextField(processedSpeech, 0, 16); m_textfield.multiline = true; m_textfield.wordWrap = true; m_container.addChild(m_textfield); m_textfield.x = 15; m_textfield.y = 3; this.visible = false; this.addEventListener(Event.ENTER_FRAME, tickOnce, false, 0, true); } private function tickOnce(a_event:Event):void{ this.removeEventListener(Event.ENTER_FRAME, tickOnce, false); this.visible = true; var textWidth = 120; m_textfield.width = textWidth; m_speechBubble.width = int(((m_textfield.width + m_textfield.x) + 10)); if ((m_speechBubble.width % 2) == 0){ m_speechBubble.width = (m_speechBubble.width - 1); }; m_speechBubble.height = int(((48 - 14) + (16 * m_textfield.numLines))); m_container.y = -(m_speechBubble.height); } } }//package game.ui
Section 234
//Splash (game.ui.Splash) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.text.*; import caurina.transitions.*; import flash.net.*; import flash.filters.*; public class Splash extends Sprite { private var m_container:Sprite; public function Splash(){ super(); m_container = new Sprite(); var headerText:String = ""; headerText = "TMNT Smash Up available now:"; var results:TextField = createTextField(headerText, 20, 330); results.autoSize = "center"; results.text = results.text; results.x = int(results.x); results.y = int(results.y); m_container.addChild(results); var packArt:Sprite = new Sprite(); packArt.addChild(new AssetLibrary.PACKSHOT_LARGE()); if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ packArt.addEventListener(MouseEvent.MOUSE_OVER, glow); packArt.addEventListener(MouseEvent.MOUSE_OUT, unglow); packArt.buttonMode = true; }; packArt.x = int(((m_container.width / 2) - (packArt.width / 2))); packArt.y = 65; m_container.addChild(packArt); m_container.width = int(m_container.width); m_container.height = int(m_container.height); var loading:TextField = createTextField("Loading...", 20, 200); loading.autoSize = "center"; loading.text = loading.text; loading.x = (m_container.width - loading.width); loading.y = m_container.height; m_container.addChild(loading); var popUp:Popup = new Popup(m_container, 100, 60); popUp.name = "popup"; if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ popUp.addEventListener(MouseEvent.CLICK, click); }; addChild(popUp); Tweener.addTween(popUp, {delay:3.5, time:1.5, onComplete:kill, onCompleteParams:[]}); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 250; }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.width = a_width; addChild(textfield); return (textfield); } private function kill():void{ this.getChildByName("popup").removeEventListener(MouseEvent.CLICK, click); parent.addChild(new Title()); parent.removeChild(this); } private function unglow(a_event:Event):void{ a_event.target.filters = []; } private function click(a_e:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_SITE_LINK); navigateToURL(target, "_blank"); } private function glow(a_event:Event):void{ a_event.target.filters = [new GlowFilter(0xFFFFFF, 1, 6, 6, 5)]; } } }//package game.ui
Section 235
//StatisticsScreen (game.ui.StatisticsScreen) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; import flash.text.*; import com.urbansquall.ui.*; import game.*; import com.urbansquall.utils.*; import flash.filters.*; public class StatisticsScreen extends Sprite { private var m_gameEndScreen:GameEndScreen; private var m_paddingBetweenYs:Number;// = 40 private var m_lineY:Number;// = 40 private var m_container:Sprite; public function StatisticsScreen(a_statistics:Statistics, a_victory:Boolean, a_primaryTurtle:String, a_gameEndScreen:GameEndScreen){ super(); m_gameEndScreen = a_gameEndScreen; m_container = new Sprite(); var headerText:String = ""; if (a_victory){ headerText = "You Won!"; } else { headerText = "You Lost!"; }; var results:TextField = createTextField(headerText, 24); m_container.addChild(results); createLine("sword_ninja", "death", "death_final", Statistics.ENEMIES_KILLED, (a_statistics.readStat(Statistics.ENEMIES_KILLED) + "")); createLine(a_primaryTurtle.toLowerCase(), "crouchattack", "attackNext", Statistics.LARGEST_COMBO, (a_statistics.readStat(Statistics.LARGEST_COMBO) + "")); createLine(a_primaryTurtle.toLowerCase(), "walk", "step", Statistics.TIME_TAKEN, StringUtils.convertToClockTime(a_statistics.readStat(Statistics.TIME_TAKEN))); var nextButton:VistaButton = TMNTButtonFactory.instance.createButton("Next"); nextButton.x = int((m_container.width - nextButton.width)); nextButton.y = int(m_lineY); nextButton.addEventListener(MouseEvent.CLICK, close); m_container.addChild(nextButton); var popUp:Popup = new Popup(m_container, 60, 60); addChild(popUp); } private function forceLoop(a_animationEvent:AnimationEvent):void{ var ginger:AnimationPlayer; if (!a_animationEvent.begin){ ginger = (a_animationEvent.currentTarget as AnimationPlayer); if (a_animationEvent.animationID != "death"){ ginger.play(a_animationEvent.animationID); } else { ginger.stopSelfTick(); }; }; } public function createLine(a_ginger:String, a_animation:String, a_frame:String, a_description:String, a_score:String):void{ var lineContainer:Sprite = new Sprite(); m_container.addChild(lineContainer); lineContainer.y = m_lineY; var ginger:AnimationPlayer = GingerFactory.getInstance().instantiate(a_ginger); ginger.x = (ginger.x + 40); ginger.y = (ginger.y + 40); ginger.scaleX = 0.5; ginger.scaleY = 0.5; lineContainer.addChild(ginger); ginger.startSelfTick(33); ginger.play(a_animation); ginger.defaultAnimationID = a_animation; if (a_animation == "death"){ ginger.x = (ginger.x + 10); ginger.y = (ginger.y - 5); }; ginger.addEventListener(AnimationEvent.CHANGE, forceLoop, false, 0, true); if (a_frame != ""){ }; var description:DefaultTextField = createTextField(a_description); lineContainer.addChild(description); description.x = 40; var score:DefaultTextField = createTextField(a_score, 16, 50); lineContainer.addChild(score); score.x = 300; m_lineY = (m_lineY + m_paddingBetweenYs); } private function createTextField(a_text:String, a_textSize:int=16, a_width:int=-1):DefaultTextField{ var textfield:DefaultTextField; if (a_width < 0){ a_width = 250; }; var textColor:uint = 0xFFFFFF; textfield = new DefaultTextField(a_text, textColor, a_textSize); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.autoSize = "center"; textfield.wordWrap = true; textfield.multiline = true; textfield.width = a_width; addChild(textfield); return (textfield); } private function close(a_event:Event):void{ m_gameEndScreen.visible = true; this.parent.removeChild(this); } } }//package game.ui
Section 236
//StoryNode (game.ui.StoryNode) package game.ui { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import com.urbansquall.prophet.display.*; public class StoryNode extends Sprite { private var m_story:Story;// = null private var m_playStoryFunc:Function;// = null public function StoryNode(a_story:Story, a_playStoryFunc:Function){ super(); m_story = a_story; m_playStoryFunc = a_playStoryFunc; var ginger:AnimationPlayer = GingerFactory.getInstance().instantiate("level_marker"); ginger.play("story"); addChild(ginger); buttonMode = false; disable(); } public function disable():void{ alpha = 0.3; mouseEnabled = false; } public function onClick(e:MouseEvent):void{ m_playStoryFunc(m_story); } public function enable():void{ TMNTToolTip.attachToolTip(this, ("Story " + m_story.levelNum.toString())); this.addEventListener(MouseEvent.CLICK, onClick); buttonMode = true; alpha = 1; mouseEnabled = true; } } }//package game.ui
Section 237
//StoryScreen (game.ui.StoryScreen) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import caurina.transitions.*; import com.urbansquall.audio.*; import flash.utils.*; public class StoryScreen extends Sprite { private var m_storyClip:MovieClip; private var m_frameRate:Number; public function StoryScreen(a_storyClip:MovieClip){ super(); m_storyClip = a_storyClip; addChild(m_storyClip); this.addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true); } private function addedToStage(a_event:Event):void{ var musicClass:Class; var a_event = a_event; this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage); m_frameRate = this.stage.frameRate; this.stage.frameRate = 30; this.addEventListener(Event.ENTER_FRAME, tick, false, 0, true); if (Constants.MUSIC_ENABLED){ SoundSystem.instance.destroyLoop("ui_background"); musicClass = (getDefinitionByName("MUSIC_BOSS") as Class); //unresolved jump var _slot1 = e; musicClass = null; if (musicClass == null){ SoundSystem.instance.createLoop("background", new MUSIC_IN_GAME()); } else { SoundSystem.instance.createLoop("background", new (musicClass)); }; }; var muteButton:DisplayObject = this.stage.getChildByName("muteButton"); muteButton.visible = false; } private function tick(a_event:Event):void{ if (m_storyClip.currentFrame >= (m_storyClip.totalFrames - 1)){ this.removeEventListener(Event.ENTER_FRAME, tick); m_storyClip.stop(); Tweener.addTween(this, {alpha:0, time:1, delay:2, onComplete:finish, onCompleteParams:[]}); dispatchEvent(new Event(Event.COMPLETE)); this.parent.setChildIndex(this, (this.parent.numChildren - 1)); return; }; } private function finish():void{ var muteButton:DisplayObject = this.stage.getChildByName("muteButton"); muteButton.visible = true; this.stage.frameRate = m_frameRate; m_storyClip.stop(); this.parent.removeChild(this); } } }//package game.ui
Section 238
//Title (game.ui.Title) package game.ui { import flash.events.*; import flash.display.*; import shared.*; import flash.text.*; import caurina.transitions.*; import com.urbansquall.audio.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.tilemaps.editor.*; import flash.utils.*; import game.*; import Box2D.Dynamics.*; import flash.net.*; import flash.filters.*; public class Title extends Sprite { private var m_creditsButton:VistaButton; private static var m_background:Sprite; private static var m_characterSelectButton:VistaButton; private static var m_editorButton:VistaButton; private static var m_buttonContainer:Sprite; private static var m_editCampaignButton:VistaButton; private static var s_instance:Title; private static var m_editTileMapButton:VistaButton; private static var m_enterFriendsCodeInput:TextField; private static var m_campaignButton:VistaButton; private static var m_mode:DisplayObject; private static var m_uiContainer:Sprite; public function Title(){ super(); s_instance = this; this.addEventListener(Event.ADDED_TO_STAGE, drawUI); } private function ubiLogoClick(a_event:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_SITE_LINK); navigateToURL(target, "_blank"); } private function unglow(a_event:Event):void{ a_event.target.filters = []; } private function clickPutThisGame(a_event:Event):void{ var target:URLRequest = new URLRequest(Constants.PUT_THIS_GAME_ON_YOUR_SITE_LINK); navigateToURL(target, "_blank"); } private function drawUI(a_event:Event):void{ var musicClass:Class; var button:DisplayObject; var putThisButton:Sprite; var a_event = a_event; this.removeEventListener(Event.ADDED_TO_STAGE, drawUI); if (((!(SoundSystem.instance.isPlaying("ui_background"))) && (Constants.MUSIC_ENABLED))){ musicClass = null; musicClass = (getDefinitionByName("MUSIC_UI") as Class); //unresolved jump var _slot1 = e; musicClass = null; if (musicClass != null){ SoundSystem.instance.createLoop("ui_background", new (musicClass)); } else { SoundSystem.instance.createLoop("ui_background", new MUSIC_IN_GAME()); }; }; m_uiContainer = new Sprite(); addChild(m_uiContainer); m_buttonContainer = new Sprite(); addChild(m_buttonContainer); m_uiContainer.y = int((1.5 * Constants.RENDER_HEIGHT)); if (!Constants.ALLOW_DEBUG){ Tweener.addTween(m_uiContainer, {y:0, time:1.5, transition:"linear"}); } else { m_uiContainer.y = 0; }; m_background = new Sprite(); m_background.addChild(new AssetLibrary.ROOFTOP_STATIC_BG()); m_uiContainer.addChild(m_background); var packArt:Sprite = new Sprite(); packArt.addChild(new AssetLibrary.PACKSHOT_SMALL()); packArt.x = 12; packArt.y = ((m_background.height - packArt.height) - 30); if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ packArt.addEventListener(MouseEvent.MOUSE_OVER, glow); packArt.addEventListener(MouseEvent.MOUSE_OUT, unglow); packArt.addEventListener(MouseEvent.CLICK, packArtClick); packArt.buttonMode = true; }; m_background.addChild(packArt); var ubiLogo:Sprite = new Sprite(); ubiLogo.addChild(new AssetLibrary.UBISOFT_LOGO()); ubiLogo.x = ((m_background.width - ubiLogo.width) - 35); ubiLogo.y = ((m_background.height - ubiLogo.height) - 30); ubiLogo.name = "ubi"; if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_LINKS)){ ubiLogo.addEventListener(MouseEvent.MOUSE_OVER, glow); ubiLogo.addEventListener(MouseEvent.MOUSE_OUT, unglow); ubiLogo.addEventListener(MouseEvent.CLICK, ubiLogoClick); ubiLogo.buttonMode = true; }; m_background.addChild(ubiLogo); m_editCampaignButton = TMNTButtonFactory.instance.createButton("[Edit Campaign]"); m_editCampaignButton.width = 160; m_editCampaignButton.x = (this.stage.stageWidth - m_editCampaignButton.width); m_editCampaignButton.addEventListener(MouseEvent.CLICK, clickEditCampaign); m_uiContainer.addChild(m_editCampaignButton); m_editTileMapButton = TMNTButtonFactory.instance.createButton("[Edit Level]"); m_editTileMapButton.width = 160; m_editTileMapButton.x = (this.stage.stageWidth - m_editTileMapButton.width); m_editTileMapButton.y = m_editCampaignButton.height; m_editTileMapButton.addEventListener(MouseEvent.CLICK, clickEditTileMap); m_uiContainer.addChild(m_editTileMapButton); if (!Constants.ALLOW_DEBUG){ m_editTileMapButton.visible = false; m_editCampaignButton.visible = false; m_editTileMapButton.removeEventListener(MouseEvent.CLICK, clickEditCampaign); m_editCampaignButton.removeEventListener(MouseEvent.CLICK, clickEditCampaign); }; var buttons:Array = []; m_campaignButton = TMNTButtonFactory.instance.createButton("Play"); m_campaignButton.addEventListener(MouseEvent.CLICK, clickCampaign); buttons.push(m_campaignButton); var helpButton:VistaButton = TMNTButtonFactory.instance.createButton("Help"); helpButton.addEventListener(MouseEvent.CLICK, clickHelp); buttons.push(helpButton); m_creditsButton = TMNTButtonFactory.instance.createButton("Credits"); m_creditsButton.addEventListener(MouseEvent.CLICK, clickCredits); buttons.push(m_creditsButton); var i:int; while (i < buttons.length) { button = buttons[i]; m_buttonContainer.addChild(button); button.width = 160; button.x = ((this.stage.stageWidth / 2) - (button.width / 2)); button.y = int(((280 + (i * m_campaignButton.height)) + 5)); button.alpha = 0; button.visible = false; if (!Constants.ALLOW_DEBUG){ Tweener.addTween(button, {alpha:1, delay:1.5, time:0.25, onStart:makeVisible, onStartParams:[button]}); } else { button.alpha = 1; button.visible = true; if ((((button == m_creditsButton)) && ((Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_CREDITS)))){ m_creditsButton.visible = false; }; }; i = (i + 1); }; if (!Constants.LITE_VERSION){ putThisButton = new Sprite(); putThisButton.x = 3; putThisButton.y = 3; m_uiContainer.addChild(putThisButton); putThisButton.buttonMode = true; putThisButton.addChild(new AssetLibrary.PUT_THIS_GAME()); putThisButton.addEventListener(MouseEvent.CLICK, clickPutThisGame); putThisButton.addEventListener(MouseEvent.MOUSE_OVER, glow); putThisButton.addEventListener(MouseEvent.MOUSE_OUT, unglow); }; var titleLogo:DisplayObject = new AssetLibrary.TITLE_LOGO(); titleLogo.x = ((Constants.RENDER_WIDTH / 2) - (titleLogo.width / 2)); titleLogo.y = ((m_uiContainer.height - titleLogo.height) - 100); m_uiContainer.addChild(titleLogo); } private function makeVisible(a_displayObject:DisplayObject):void{ if ((((a_displayObject == m_creditsButton)) && ((Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_CREDITS)))){ m_creditsButton.visible = false; } else { a_displayObject.visible = true; }; } private function glow(a_event:Event):void{ if (a_event.target.name == "ubi"){ a_event.target.filters = [new GlowFilter(0, 1, 6, 6, 5)]; } else { a_event.target.filters = [new GlowFilter(0xFFFFFF, 1, 6, 6, 5)]; }; } private function packArtClick(a_event:Event):void{ var target:URLRequest = new URLRequest(Constants.UBI_BUY_NOW_LINK); navigateToURL(target, "_blank"); } public static function gotoMainMenu():void{ if ((m_mode is Game)){ (m_mode as Game).dispose(); }; s_instance.removeChild(m_mode); m_uiContainer.visible = true; m_buttonContainer.visible = true; } private static function clickHelp(a_event:Event):void{ m_uiContainer.visible = false; m_buttonContainer.visible = false; var helpScreen:HelpScreen = new HelpScreen(); helpScreen.addEventListener(Event.COMPLETE, complete, false, 0, true); s_instance.addChild(helpScreen); m_mode = helpScreen; } private static function clickEditCampaign(a_event:Event):void{ m_uiContainer.visible = false; m_buttonContainer.visible = false; var campaignScreen:CampaignScreen = new CampaignScreen(true); campaignScreen.addEventListener(Event.COMPLETE, complete, false, 0, true); s_instance.addChild(campaignScreen); m_mode = campaignScreen; } private static function clickCredits(a_event:Event):void{ m_uiContainer.visible = false; m_buttonContainer.visible = false; var creditsScreen:CreditsScreen = new CreditsScreen(); creditsScreen.addEventListener(Event.COMPLETE, complete, false, 0, true); s_instance.addChild(creditsScreen); m_mode = creditsScreen; } private static function clickCampaign(a_event:Event):void{ m_uiContainer.visible = false; m_buttonContainer.visible = false; var campaignScreen:CampaignScreen = new CampaignScreen(); campaignScreen.addEventListener(Event.COMPLETE, complete, false, 0, true); s_instance.addChild(campaignScreen); m_mode = campaignScreen; } private static function complete(a_event:Event):void{ gotoMainMenu(); } private static function clickEditTileMap(a_event:Event):void{ m_uiContainer.visible = false; m_buttonContainer.visible = false; var tileMapEditor:LevelEditor = new LevelEditor(new TMNTGameDefinition(), new TMNTTileLibrary(), [2, 1, 0]); tileMapEditor.addEventListener(Event.COMPLETE, complete, false, 0, true); s_instance.addChild(tileMapEditor); tileMapEditor.load(null); m_mode = tileMapEditor; } } }//package game.ui
Section 239
//AttackManager (game.AttackManager) package game { import shared.*; import com.urbansquall.prophet.engine.*; import game.events.*; public class AttackManager { public function AttackManager(){ super(); } public static function enemyAttack(a_enemy:Entity, a_object:Entity, a_damage:int):void{ if (!a_object.properties.getBoolean("isTurtle", false)){ return; }; if (a_object.properties.getInt("invincibleTimer", 0) > 0){ return; }; a_object.properties.setBoolean("shellAttacking", false); Gameplay.hurtPlayer(a_object, a_damage); a_object.properties.setInt("invincibleTimer", Constants.INVINCIBILITY_TIME); if (a_object.getPosition().x > a_enemy.getPosition().x){ a_object.properties.setInt("flinchingDir", 1); } else { a_object.properties.setInt("flinchingDir", -1); }; a_object.properties.setBoolean("isFlinching", true); a_object.getEngine().dispatchEvent(new ComboEvent(ComboEvent.COMBO_RESET)); } public static function turtleAttack(a_turtle:Entity, a_object:Entity, a_knockback:Boolean, a_halfDamage:Boolean):void{ var turtleAttackStrength:Number = 0; var strongAgainst:String = "none"; switch (a_turtle.type){ case Constants.ENTITY_TYPE_LEONARDO: turtleAttackStrength = 100; strongAgainst = "humans"; break; case Constants.ENTITY_TYPE_RAPHAEL: turtleAttackStrength = 115; strongAgainst = "humans"; break; case Constants.ENTITY_TYPE_MICHELANGELO: turtleAttackStrength = 115; strongAgainst = "robots"; break; case Constants.ENTITY_TYPE_DONATELLO: turtleAttackStrength = 100; strongAgainst = "robots"; break; default: trace("unidentified attacker in AttackManager.as, proceeding as if its Leo"); turtleAttackStrength = 100; strongAgainst = "humans"; break; }; var flinchDirection = 1; if (a_object.getPosition().x > a_turtle.getPosition().x){ flinchDirection = 1; } else { flinchDirection = -1; }; if (a_halfDamage){ turtleAttackStrength = (turtleAttackStrength / 2); }; doTurtleAttack(a_object, turtleAttackStrength, strongAgainst, flinchDirection, a_knockback); } public static function doTurtleAttack(a_object:Entity, a_damageAmount:Number, a_damageType:String, a_flinchDirection:int, a_knockback:Boolean):void{ if (!a_object.properties.getBoolean("isEnemy", false)){ return; }; var turtleAttackStrength:int = a_damageAmount; var strongAgainst:String = a_damageType; var isHuman:Boolean = a_object.properties.getBoolean("isHuman", false); if ((((((strongAgainst == "humans")) && (isHuman))) || ((((strongAgainst == "robots")) && (!(isHuman)))))){ turtleAttackStrength = (turtleAttackStrength * Constants.ATTACK_MULTIPLIER_STRONG); } else { if (!a_object.properties.getBoolean("isInanimate", false)){ turtleAttackStrength = (turtleAttackStrength * Constants.ATTACK_MULTIPLIER_WEAK); }; }; var currentLives:int = a_object.properties.getInt("lives", 0); a_object.properties.setInt("lives", (currentLives - turtleAttackStrength)); currentLives = a_object.properties.getInt("lives", 0); if (currentLives > 0){ a_object.properties.setBoolean("isFlinching", true); }; a_object.properties.setBoolean("hasKnockback", a_knockback); a_object.properties.setInt("flinchingDir", a_flinchDirection); a_object.getEngine().dispatchEvent(new ComboEvent(ComboEvent.COMBO_UP)); } } }//package game
Section 240
//Effects (game.Effects) package game { import com.urbansquall.ginger.*; import flash.display.*; import com.urbansquall.prophet.display.*; import caurina.transitions.*; public class Effects { public function Effects(){ super(); } public static function drawTurtleAttackEffect(a_x:int, a_y:int, a_container:DisplayObjectContainer, a_positionalVariance:int=10):void{ var type = ((Math.floor((Math.random() * 3)) + 1) + ""); var effect:AnimationPlayer = GingerFactory.getInstance().instantiate(("hit_effect_" + type)); effect.play("default"); effect.startSelfTick(33); a_container.addChild(effect); var randomizedOffset:int = a_positionalVariance; effect.x = (a_x + ((Math.random() * randomizedOffset) - (randomizedOffset / 2))); effect.y = (a_y + ((Math.random() * randomizedOffset) - (randomizedOffset / 2))); Tweener.addTween(effect, {alpha:0, delay:1, onComplete:effect.parent.removeChild, onCompleteParams:[effect]}); } } }//package game
Section 241
//Game (game.Game) package game { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.audio.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import game.events.*; import com.urbansquall.prophet.events.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import com.urbansquall.prophet.input.*; import flash.utils.*; import Box2D.Common.Math.*; import game.ui.*; import Box2D.Dynamics.*; import com.urbansquall.prophet.behaviors.*; import game.behaviors.*; public class Game extends Sprite { private var m_levelBackground:LevelBackground;// = null private var m_playerStateMachine:PlayerStateMachine; private var m_roomContainer:Sprite; private var m_inGameOptions:InGameOptions;// = null private var m_inGameOptionsPopup:Popup;// = null private var m_effectContainer:Sprite; private var m_playerWon:Boolean;// = false private var m_hud:GameHUD; private var m_wallLock:Boolean;// = false private var m_pregamePopup:Sprite;// = null private var m_levelDefinition:LevelDefinition; private var m_container:Sprite; private var m_statistics:Statistics; private var m_canWallJump:Boolean;// = true private var m_combo:int;// = 0 private var m_secondaryCharacter:String; private var m_score:int;// = 0 private var m_viewTargetID:String;// = "" private var m_engine:Engine; private var m_primaryCharacter:String; private var m_optionsShowing:Boolean;// = false private var m_gameHasEnded:Boolean;// = false private var m_processedLevel:LevelDefinition; private var m_comboTimer:Number;// = 0 private var m_cameraOffsetX:Number;// = 100 private var m_gameDefinition:GameDefinition; public static const MAX_CAMERA_OFFSET:Number = 100; public static const BOUNDARY_THICKNESS:Number = 100; public function Game(a_gameDefinition:GameDefinition){ super(); m_gameDefinition = a_gameDefinition; } private function onTouchedPool(a_event:Event):void{ var player:Entity = m_engine.lookupEntity("my_player"); var safePositions:Array = m_playerStateMachine.safePositions; var safeSpot:Point = safePositions[(safePositions.length - 2)]; safePositions.splice((safePositions.length - 2), 2); if (safePositions.length == 0){ player.properties.setInt("health", 0); return; }; Gameplay.hurtPlayer(player, 2, 0); player.properties.setInt("invincibleTimer", Constants.INVINCIBILITY_TIME); player.properties.setBoolean("hasDoubleJumped", false); player.setPosition(safeSpot.x, safeSpot.y); player.setVelocity(0, 0); } private function remove():void{ } private function onChangeScore(a_scoreEvent:ChangeScoreEvent):void{ if (a_scoreEvent.amount == 0){ return; }; m_score = (m_score + a_scoreEvent.amount); var scoreText = (a_scoreEvent.amount + ""); if (a_scoreEvent.amount > 0){ scoreText = ("+" + scoreText); }; var scoreDisplay:DefaultTextField = new DefaultTextField(scoreText, 0xFFFFFF); scoreDisplay.x = (a_scoreEvent.x - (scoreDisplay.width / 2)); scoreDisplay.y = (a_scoreEvent.y - (scoreDisplay.height / 2)); Tweener.addTween(scoreDisplay, {y:(scoreDisplay.y - 50), time:0.75}); Tweener.addTween(scoreDisplay, {alpha:0, delay:0.75, time:0.3, onComplete:removeGraphic, onCompleteParams:[scoreDisplay]}); getEngine().renderer.addDisplayObject(scoreDisplay, (Constants.ENTITY_DEFAULT_RENDER_LAYER + 1000)); } public function onUpdate(a_event:UpdateEvent):void{ var fadeToBlack:Sprite; var mouseX:Number; var mouseY:Number; var spawnType:String; var spawnInfo:EntitySpawnInfo; if (m_gameHasEnded){ return; }; if (m_engine.isPaused()){ return; }; var interval:Number = a_event.interval; m_comboTimer = (m_comboTimer - interval); if (m_comboTimer <= 0){ m_combo = 0; }; m_statistics.maxStat(Statistics.LARGEST_COMBO, m_combo); m_statistics.increaseStat(Statistics.TIME_TAKEN, interval); var keyboardState:KeyboardState = m_engine.keyboardState; var player:Entity = m_engine.lookupEntity("my_player"); m_hud.update(); m_hud.updateCombo(m_combo, m_comboTimer); m_hud.setOozeRemaining(player.properties.getInt("ooze", 0)); m_hud.setHealthRemaining(player.properties.getInt("health", Constants.STARTING_HEALTH)); m_hud.setScore(m_score); if (player.properties.getBoolean("touchedExit", false)){ fadeToBlack = new Sprite(); fadeToBlack.graphics.beginFill(0); fadeToBlack.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); addChild(fadeToBlack); fadeToBlack.alpha = 0; Tweener.addTween(fadeToBlack, {alpha:1, time:4}); endGame(true); return; }; if (player.properties.getBoolean("dead", false)){ endGame(false); return; }; if (Constants.ALLOW_DEBUG){ if (keyboardState.wasJustPressed(KeyboardMap.HOME)){ player.properties.setBoolean("touchedExit", true); }; if (keyboardState.wasJustPressed(KeyboardMap.END)){ player.properties.setInt("health", 0); }; mouseX = m_engine.renderer.mouseX; mouseY = m_engine.renderer.mouseY; spawnType = ""; if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_1)){ spawnType = Constants.ENTITY_TYPE_SENTRY; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_2)){ spawnType = Constants.ENTITY_TYPE_MOUSER; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_3)){ spawnType = Constants.ENTITY_TYPE_SHURIKEN_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_4)){ spawnType = Constants.ENTITY_TYPE_SWORD_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.LEFTBRACKET)){ spawnType = Constants.ENTITY_TYPE_SWORD_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.RIGHTBRACKET)){ spawnType = Constants.ENTITY_TYPE_SWORD_NINJA_PASSIVE; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_5)){ spawnType = Constants.ENTITY_TYPE_BLOWGUN_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_6)){ spawnType = Constants.ENTITY_TYPE_JUMPING_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_7)){ spawnType = Constants.ENTITY_TYPE_JUGGERNAUGHT; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_8)){ spawnType = Constants.ENTITY_TYPE_SLOTH; } else { if (keyboardState.wasJustPressed(KeyboardMap.NUMBER_9)){ spawnType = Constants.ENTITY_TYPE_LASER_NINJA; } else { if (keyboardState.wasJustPressed(KeyboardMap.P)){ spawnType = Constants.ENTITY_TYPE_PIZZA; } else { if (keyboardState.wasJustPressed(KeyboardMap.T)){ spawnType = Constants.ENTITY_TYPE_FULL_PIZZA; } else { if (keyboardState.wasJustPressed(KeyboardMap.Y)){ spawnType = Constants.ENTITY_TYPE_SHREDDER; } else { if (keyboardState.wasJustPressed(KeyboardMap.U)){ spawnType = Constants.ENTITY_TYPE_SUPER_SHREDDER; } else { if (keyboardState.wasJustPressed(KeyboardMap.I)){ spawnType = Constants.ENTITY_TYPE_HUN; } else { if (keyboardState.wasJustPressed(KeyboardMap.PERIOD)){ spawnType = Constants.ENTITY_TYPE_OOZE_CANNISTER; } else { if (keyboardState.wasJustPressed(KeyboardMap.COMMA)){ spawnType = Constants.ENTITY_TYPE_OOZE_CAN; } else { if (keyboardState.wasJustPressed(KeyboardMap.BACKSLASH)){ spawnType = Constants.ENTITY_TYPE_LINEAR_SENTRY; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; if (spawnType != ""){ spawnInfo = new EntitySpawnInfo(spawnType, "", mouseX, mouseY, 0, 0, 0, 1, null); m_engine.createEntity(spawnInfo); }; }; if (((keyboardState.isDown(KeyboardMap.LEFT)) && ((player.getVelocity().x < -2)))){ m_cameraOffsetX = (m_cameraOffsetX - 2); }; if (((keyboardState.isDown(KeyboardMap.RIGHT)) && ((player.getVelocity().x > 2)))){ m_cameraOffsetX = (m_cameraOffsetX + 2); }; m_playerStateMachine.update(interval); if (keyboardState.wasJustPressed(KeyboardMap.ESCAPE)){ showOptions(); }; var viewTarget:Entity; if (m_viewTargetID != ""){ viewTarget = m_engine.lookupEntity(m_viewTargetID); }; if (viewTarget == null){ m_engine.renderer.view.speedX = 0.2; m_engine.renderer.view.tensionX = 0.1; m_cameraOffsetX = Math.max(m_cameraOffsetX, -(MAX_CAMERA_OFFSET)); m_cameraOffsetX = Math.min(m_cameraOffsetX, MAX_CAMERA_OFFSET); updateViewTarget((player.getPosition().x + m_cameraOffsetX), player.getPosition().y); } else { m_engine.renderer.view.speedX = 0.02; m_engine.renderer.view.tensionX = 0.07; updateViewTarget(viewTarget.getPosition().x, viewTarget.getPosition().y); }; m_levelBackground.update(m_engine.renderer.view.viewX, m_engine.renderer.view.viewY); } private function removeGraphic(a_displayObject:DisplayObject):void{ getEngine().renderer.removeDisplayObject(a_displayObject); } public function onCompleteDizzyAnimation(a_event:AnimationEvent):void{ if (!a_event.begin){ endGame(false); }; } private function closeOptions(a_event:Event):void{ removeChild(m_inGameOptionsPopup); m_inGameOptions = null; m_inGameOptionsPopup = null; m_optionsShowing = false; m_engine.unpause(); } private function boxedHit(a_player:Entity, a_startX:int, a_width:int, a_height:int, a_knockback:Boolean=false):void{ var entity:Entity; var hitValue:int; var xHitSpeed:int; var yHitSpeed:int; var boxedEntities:Array = m_engine.queryBox(a_startX, a_player.getPosition().y, a_width, a_height, false); var a:int; while (a < boxedEntities.length) { entity = boxedEntities[a]; if (entity != a_player){ hitValue = 100; if (entity.properties.getBoolean("isHuman", false)){ hitValue = (hitValue * 1.2); } else { hitValue = (hitValue * 0.8); }; entity.properties.setInt("lives", (entity.properties.getInt("lives", 0) - hitValue)); if (a_knockback){ xHitSpeed = 100; if (a_player.getPosition().x > entity.getPosition().x){ xHitSpeed = (xHitSpeed * -1); }; yHitSpeed = -200; entity.setVelocity(xHitSpeed, yHitSpeed); }; }; a++; }; } public function dispose():void{ m_engine.dispose(); m_engine = null; m_hud.dispose(); m_hud = null; removeChild(m_effectContainer); m_effectContainer = null; removeChild(m_container); m_container = null; m_gameDefinition = null; m_levelDefinition = null; } private function onComboReset(a_comboEvent:ComboEvent):void{ m_combo = 0; m_comboTimer = 0; } public function get playerWon():Boolean{ return (m_playerWon); } public function getEngine():Engine{ return (m_engine); } public function changeCharacters(a_event:Event=null):void{ SoundSystem.instance.destroyLoop("background"); dispatchEvent(new Event(Event.CHANGE)); } private function showInputHelp(a_event:Event):void{ var hideInput:Boolean = SafeSol.instance.readBool("hide_input"); if (!hideInput){ removeChild(m_pregamePopup); m_pregamePopup = new RegularInputHelp(); m_pregamePopup.addEventListener(Event.CLOSE, startGame); addChild(m_pregamePopup); } else { startGame(null); }; } public function restartLevel(a_event:Event=null):void{ var target:GameEndScreen; if (a_event != null){ target = (a_event.currentTarget as GameEndScreen); target.parent.removeChild(target); }; m_hud.dispose(); m_hud.parent.removeChild(m_hud); m_hud = null; m_effectContainer.parent.removeChild(m_effectContainer); m_effectContainer = null; m_engine.clear(); m_engine.renderer.view.clearTemporaryBounds(); m_combo = 0; executeLoad(); } private function onLoaded(a_event:Event):void{ m_effectContainer = new Sprite(); addChild(m_effectContainer); m_hud = new GameHUD(this, m_primaryCharacter, m_secondaryCharacter); addChild(m_hud); var scoreToBeat:int = m_processedLevel.getDataDump().getInt(Constants.DATA_SCORE_TO_BEAT, 0); var levelInfo:PreLevelInfo = new PreLevelInfo(scoreToBeat); levelInfo.addEventListener(Event.COMPLETE, showInputHelp); m_pregamePopup = new Popup(levelInfo, 60); addChild(m_pregamePopup); m_engine.forcePrune(); } private function updateViewTarget(a_targetX:Number, a_targetY:Number):void{ m_engine.renderer.view.setTarget(a_targetX, a_targetY); } public function getScore():int{ return (m_score); } private function createWorldBoundaries(a_worldBounds:Rectangle, a_levelDefinition:LevelDefinition):void{ var entityDef:EntityTypeDefinition; var polyDef:PolygonDef; var bodyDef:b2BodyDef; a_levelDefinition.setWorldBounds(((a_worldBounds.x - BOUNDARY_THICKNESS) - 1), ((a_worldBounds.y - BOUNDARY_THICKNESS) - 1), ((a_worldBounds.width + (2 * BOUNDARY_THICKNESS)) + 1), ((a_worldBounds.height + (2 * BOUNDARY_THICKNESS)) + 1)); m_engine.removeEntityType("left_boundary"); m_engine.removeEntityType("right_boundary"); m_engine.removeEntityType("top_boundary"); m_engine.removeEntityType("bottom_boundary"); var drawBoundaries:Boolean; entityDef = new EntityTypeDefinition(); entityDef.type = "left_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((BOUNDARY_THICKNESS / 2), (a_worldBounds.height / 2)); entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; m_engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "right_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((BOUNDARY_THICKNESS / 2), (a_worldBounds.height / 2)); entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; m_engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "bottom_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((a_worldBounds.width / 2), (BOUNDARY_THICKNESS / 2)); entityDef.behaviors.push(new BehaviorDefinition(TouchPoolBehavior, "touch pool", null)); entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.allowSleep = false; entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; m_engine.addEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = "top_boundary"; entityDef.fixed = true; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.friction = 0; polyDef.restitution = 0; polyDef.density = 1; polyDef.makeCenteredBox((a_worldBounds.width / 2), (BOUNDARY_THICKNESS / 2)); entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; if (drawBoundaries){ entityDef.graphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF0000, 0xFF00)); }; m_engine.addEntityType(entityDef); } public function load(a_levelDefinition:LevelDefinition):void{ m_levelDefinition = a_levelDefinition; var renderWidth:int = Constants.RENDER_WIDTH; var renderHeight:int = Constants.RENDER_HEIGHT; m_container = new Sprite(); addChild(m_container); var debugDraw:DebugDraw = new DebugDraw(); debugDraw.drawPhysicsShapes = false; debugDraw.drawQueries = Constants.ALLOW_DEBUG; debugDraw.drawLevelBoundaries = false; var renderer:EngineRenderer = new EngineRenderer(m_container, renderWidth, renderHeight, debugDraw); var keyboardTemplate:KeyboardTemplate = new KeyboardTemplate(); keyboardTemplate.registerAction(KeyboardMap.LEFT, "Move left"); keyboardTemplate.registerAction(KeyboardMap.RIGHT, "Move right"); keyboardTemplate.registerAction(KeyboardMap.UP, "Jump"); keyboardTemplate.registerAction(KeyboardMap.SPACE, "Jump"); keyboardTemplate.registerAction(KeyboardMap.DOWN, "Crouch"); keyboardTemplate.registerAction(KeyboardMap.A, "Attack"); keyboardTemplate.registerAction(KeyboardMap.S, "Special"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_1, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_2, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_3, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_4, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_5, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_6, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_7, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_8, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_9, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.NUMBER_0, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.T, "Pizza spawn"); keyboardTemplate.registerAction(KeyboardMap.Y, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.U, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.I, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.O, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.P, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.PERIOD, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.COMMA, "Ooze spawn"); keyboardTemplate.registerAction(KeyboardMap.LEFTBRACKET, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.RIGHTBRACKET, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.BACKSLASH, "Enemy spawn"); keyboardTemplate.registerAction(KeyboardMap.HOME, "Win"); keyboardTemplate.registerAction(KeyboardMap.END, "Lose"); keyboardTemplate.registerAction(KeyboardMap.ESCAPE, "Pause"); m_engine = new Engine(renderer, keyboardTemplate, true, false); m_engine.removeEventListener(EngineEvent.INITIALIZED, onInitialized, false); m_engine.addEventListener(EngineEvent.INITIALIZED, onInitialized, false, 0, true); m_engine.initialize(m_gameDefinition); } private function endGame(a_victory:Boolean):void{ m_playerWon = a_victory; m_gameHasEnded = true; m_engine.pause(); var gameEndScreen:GameEndScreen = new GameEndScreen(m_score, a_victory, (m_processedLevel.getDataDump().getInt(Constants.DATA_LEVEL_INDEX, 0) + 1)); gameEndScreen.visible = false; gameEndScreen.addEventListener(Event.CLOSE, close); gameEndScreen.addEventListener(Event.OPEN, restartLevel); gameEndScreen.addEventListener(Event.CHANGE, changeCharacters); addChild(gameEndScreen); var statisticsScreen:Sprite = new StatisticsScreen(m_statistics, a_victory, m_primaryCharacter, gameEndScreen); statisticsScreen.addEventListener(Event.CLOSE, gameEndScreen.makeVisible, true, 0, true); addChild(statisticsScreen); } public function showOptions():void{ if (!m_optionsShowing){ m_engine.pause(); m_inGameOptions = new InGameOptions(this, KeyboardMap.ESCAPE); m_inGameOptions.addEventListener(Event.CLOSE, closeOptions); m_inGameOptionsPopup = new Popup(m_inGameOptions, 70, 70); addChild(m_inGameOptionsPopup); m_optionsShowing = true; }; } private function onComboUp(a_comboEvent:ComboEvent):void{ m_combo = (m_combo + 1); m_comboTimer = Constants.COMBO_TIMER; } private function onStatChange(a_statChange:ChangeStatisticEvent):void{ m_statistics.increaseStat(a_statChange.name, a_statChange.value); } private function startGame(a_event:Event):void{ var fps:FPS; m_statistics = new Statistics(); removeChild(m_pregamePopup); m_pregamePopup = null; m_engine.removeEventListener(ChangeStatisticEvent.CHANGE_STAT, onStatChange, false); m_engine.addEventListener(ChangeStatisticEvent.CHANGE_STAT, onStatChange, false, 0, true); m_engine.removeEventListener(EngineEvent.UPDATE, onUpdate, false); m_engine.addEventListener(EngineEvent.UPDATE, onUpdate, false, 0, true); m_engine.removeEventListener(ComboEvent.COMBO_UP, onComboUp, false); m_engine.addEventListener(ComboEvent.COMBO_UP, onComboUp, false, 0, true); m_engine.removeEventListener(ComboEvent.COMBO_RESET, onComboReset, false); m_engine.addEventListener(ComboEvent.COMBO_RESET, onComboReset, false, 0, true); m_engine.removeEventListener(TouchPoolEvent.TOUCHED_POOL, onTouchedPool, false); m_engine.addEventListener(TouchPoolEvent.TOUCHED_POOL, onTouchedPool, false, 0, true); m_engine.removeEventListener(ChangeViewTargetEvent.CHANGE_VIEW_TARGET, onChangeViewTarget, false); m_engine.addEventListener(ChangeViewTargetEvent.CHANGE_VIEW_TARGET, onChangeViewTarget, false, 0, true); m_engine.removeEventListener(ChangeScoreEvent.CHANGE_SCORE, onChangeScore, false); m_engine.addEventListener(ChangeScoreEvent.CHANGE_SCORE, onChangeScore, false, 0, true); if (Constants.ALLOW_DEBUG){ fps = new FPS(); fps.x = (Constants.RENDER_WIDTH / 2); fps.y = (Constants.RENDER_HEIGHT - fps.height); addChild(fps); }; m_engine.start(); m_viewTargetID = ""; m_playerStateMachine = new PlayerStateMachine(m_engine.lookupEntity("my_player"), m_engine.keyboardState, m_canWallJump); } private function executeLoad():void{ var propertyXML:XML; var selectedTurtle:String; var e:int; var entitySpawnInfo:EntitySpawnInfo; var key:String; var value:String; var musicClass:Class; var tempViewBoundX:Number; var tempViewBoundY:Number; var tempViewBoundWidth:Number; var tempViewBoundHeight:Number; var def:EntityTypeDefinition; var s:int; var shape:ShapeDef; m_score = 0; m_gameHasEnded = false; m_engine.removeEventListener(EngineEvent.LOAD, onLoaded, false); m_engine.addEventListener(EngineEvent.LOAD, onLoaded, false, 0, true); var levelDefinition:LevelDefinition = m_levelDefinition.clone(); levelDefinition.setAllowSleep(true); levelDefinition.setGravity(0, 18); levelDefinition.setWorldBounds(0, 0, 1000, 1000); var scoreToBeat:int = levelDefinition.getDataDump().getInt(Constants.DATA_SCORE_TO_BEAT, 0); var levelIndex:int = levelDefinition.getDataDump().getInt(Constants.DATA_LEVEL_INDEX, 0); var levelXML:XML = LevelData.readLevel(levelIndex); if (levelXML == null){ throw (new Error((("No level defined for index [" + levelIndex) + "]. Define it in LevelData.init."))); }; var levelPropertiesList:XMLList = levelXML.property; for each (propertyXML in levelPropertiesList) { key = propertyXML.@key; value = propertyXML.@value; levelDefinition.getDataDump().setString(key, value); }; m_canWallJump = levelDefinition.getDataDump().getBoolean("wallJumpingEnabled", true); SoundSystem.instance.destroyLoop("ui_background"); if (Constants.MUSIC_ENABLED){ musicClass = (getDefinitionByName("MUSIC_BOSS") as Class); //unresolved jump var _slot1 = e; musicClass = null; if ((((musicClass == null)) || ((levelDefinition.getDataDump().getString("music", "") == "")))){ SoundSystem.instance.createLoop("background", new MUSIC_IN_GAME()); } else { SoundSystem.instance.createLoop("background", new (musicClass)); }; }; var fillTile:String = levelDefinition.getDataDump().getString("fillTile", ""); var worldBounds:Rectangle = TileMapDefinitionXMLFormat.toLevelDefinitionFromXML(m_engine, levelDefinition, new TMNTTileLibrary(), (levelXML.tileMap[0] as XML), (Constants.ENTITY_DEFAULT_RENDER_LAYER - 50), fillTile); createWorldBoundaries(worldBounds, levelDefinition); trace(("world bounds " + worldBounds)); if (m_levelBackground == null){ m_levelBackground = new LevelBackground(levelDefinition.getDataDump().getString("background", LevelBackground.NONE), (worldBounds.y + worldBounds.height)); addChildAt(m_levelBackground, 0); }; m_engine.renderer.view.setBounds(worldBounds.x, worldBounds.y, worldBounds.width, worldBounds.height); m_levelBackground.setBounds(worldBounds.x, worldBounds.y, worldBounds.width, worldBounds.height); if (levelDefinition.getDataDump().exists("tempViewBoundX")){ tempViewBoundX = levelDefinition.getDataDump().getNumber("tempViewBoundX", 0); tempViewBoundY = levelDefinition.getDataDump().getNumber("tempViewBoundY", 0); tempViewBoundWidth = levelDefinition.getDataDump().getNumber("tempViewBoundWidth", 0); tempViewBoundHeight = levelDefinition.getDataDump().getNumber("tempViewBoundHeight", 0); m_engine.renderer.view.setTemporaryBounds(tempViewBoundX, tempViewBoundY, tempViewBoundWidth, tempViewBoundHeight); }; m_primaryCharacter = levelDefinition.getDataDump().getString(Constants.DATA_SELECTED_PRIMARY, ""); switch (m_primaryCharacter){ case "": selectedTurtle = Constants.ENTITY_TYPE_LEONARDO; break; case Constants.CHARACTER_LEONARDO: selectedTurtle = Constants.ENTITY_TYPE_LEONARDO; break; case Constants.CHARACTER_DONATELLO: selectedTurtle = Constants.ENTITY_TYPE_DONATELLO; break; case Constants.CHARACTER_RAPHAEL: selectedTurtle = Constants.ENTITY_TYPE_RAPHAEL; break; case Constants.CHARACTER_MICHELANGELO: selectedTurtle = Constants.ENTITY_TYPE_MICHELANGELO; break; }; m_secondaryCharacter = levelDefinition.getDataDump().getString(Constants.DATA_SELECTED_SECONDARY, ""); var entityList:Array = EntityDefinitionXMLFormat.fromXML((levelXML.entities[0] as XML)); e = 0; while (e < entityList.length) { entitySpawnInfo = entityList[e]; if ((((((((entitySpawnInfo.type == Constants.ENTITY_TYPE_LEONARDO)) || ((entitySpawnInfo.type == Constants.ENTITY_TYPE_DONATELLO)))) || ((entitySpawnInfo.type == Constants.ENTITY_TYPE_RAPHAEL)))) || ((entitySpawnInfo.type == Constants.ENTITY_TYPE_MICHELANGELO)))){ entitySpawnInfo.type = selectedTurtle; entitySpawnInfo.id = "my_player"; if (!m_canWallJump){ def = m_engine.lookupEntityTypeDefinition(entitySpawnInfo.type); s = 0; while (s < def.shapes.length) { shape = def.shapes[s]; shape.friction = 0; s = (s + 1); }; }; entitySpawnInfo.properties.setString(Constants.DATA_SELECTED_SECONDARY, m_secondaryCharacter); m_engine.renderer.view.setView(entitySpawnInfo.x, entitySpawnInfo.y); updateViewTarget((entitySpawnInfo.x + m_cameraOffsetX), entitySpawnInfo.y); levelDefinition.addSpawnInfo(entitySpawnInfo); entityList.splice(e, 1); break; }; e = (e + 1); }; m_engine.renderer.view.tick(0); m_levelBackground.update(m_engine.renderer.view.viewX, m_engine.renderer.view.viewY); e = 0; while (e < entityList.length) { entitySpawnInfo = entityList[e]; levelDefinition.addSpawnInfo(entitySpawnInfo); e = (e + 1); }; m_processedLevel = levelDefinition; m_engine.load(m_processedLevel); m_engine.createEntity(new EntitySpawnInfo("left_boundary", "left_boundary", (worldBounds.x - (BOUNDARY_THICKNESS / 2)), (worldBounds.y + (worldBounds.height / 2)))); m_engine.createEntity(new EntitySpawnInfo("right_boundary", "right_boundary", (worldBounds.right + (BOUNDARY_THICKNESS / 2)), (worldBounds.y + (worldBounds.height / 2)))); m_engine.createEntity(new EntitySpawnInfo("bottom_boundary", "bottom_boundary", (worldBounds.x + (worldBounds.width / 2)), (worldBounds.bottom + (BOUNDARY_THICKNESS / 2)))); m_engine.createEntity(new EntitySpawnInfo("top_boundary", "top_boundary", (worldBounds.x + (worldBounds.width / 2)), (worldBounds.top - (BOUNDARY_THICKNESS / 2)))); } private function onInitialized(a_event:Event):void{ executeLoad(); } private function onChangeViewTarget(a_event:ChangeViewTargetEvent):void{ m_viewTargetID = a_event.targetID; } public function close(a_event:Event=null):void{ SoundSystem.instance.destroyLoop("background"); dispatchEvent(new Event(Event.COMPLETE)); } } }//package game
Section 242
//GameHUD (game.GameHUD) package game { import flash.events.*; import flash.display.*; import shared.*; import caurina.transitions.*; import com.urbansquall.ui.*; import flash.utils.*; import game.ui.*; import com.urbansquall.utils.*; import flash.filters.*; public class GameHUD extends Sprite { private var m_activeStatusBox:ActiveStatusBox;// = null private var m_portraitDict:Dictionary; private var m_game:Game; private var m_scoreText:DefaultTextField; private var m_lastOoze:int; private var m_killsRequiredText:DefaultTextField;// = null private var m_secondaryTurtlePortraitContainer:Sprite;// = null private var m_inActiveStatusBox:InActiveStatusBox;// = null private var m_healthLeftText:DefaultTextField; private var m_lastHealth:int; private var m_comboContainer:ComboContainer; private var m_specialAttackOozeCost:int; private static const s_statusBoxHeight:Number = 64; private static const s_statusBoxWidth:Number = 64; private static const S_PORTRAIT_Y_MARGIN:int = 10; private static const S_PORTRAIT_X_MARGIN:int = 10; public function GameHUD(a_game:Game, a_primaryCharacter:String, a_secondaryCharacter:String){ m_portraitDict = new Dictionary(); super(); trace("characters", a_primaryCharacter, a_secondaryCharacter); m_game = a_game; m_scoreText = new DefaultTextField(); m_scoreText.visible = false; addChild(m_scoreText); m_scoreText.text = ""; var menuButton:VistaButton = TMNTButtonFactory.instance.createButton("Menu"); menuButton.width = 90; menuButton.x = (Constants.RENDER_WIDTH - menuButton.width); menuButton.y = 0; menuButton.addEventListener(MouseEvent.CLICK, clickMenu); addChild(menuButton); m_portraitDict[Constants.CHARACTER_LEONARDO.toLowerCase()] = AssetLibrary.PORTRAIT_LEONARDO; m_portraitDict[Constants.CHARACTER_DONATELLO.toLowerCase()] = AssetLibrary.PORTRAIT_DONATELLO; m_portraitDict[Constants.CHARACTER_MICHELANGELO.toLowerCase()] = AssetLibrary.PORTRAIT_MICHELANGELO; m_portraitDict[Constants.CHARACTER_RAPHAEL.toLowerCase()] = AssetLibrary.PORTRAIT_RAPHAEL; m_portraitDict[Constants.CHARACTER_PIZZA_DUDE.toLowerCase()] = AssetLibrary.PORTRAIT_PIZZA_DUDE; m_portraitDict[Constants.CHARACTER_CASEY_JONES.toLowerCase()] = AssetLibrary.PORTRAIT_CASEY_JONES; m_portraitDict[Constants.CHARACTER_SPLINTER.toLowerCase()] = AssetLibrary.PORTRAIT_SPLINTER; var portraitBorder:Sprite; var portraitClass:Class; var selectedPrimaryTurtle:String = a_primaryCharacter; var primaryTurtlePortrait:DisplayObject; var primaryTurtlePortraitContainer:Sprite; if (selectedPrimaryTurtle != ""){ portraitClass = m_portraitDict[selectedPrimaryTurtle.toLowerCase()]; primaryTurtlePortrait = (new (portraitClass) as DisplayObject); portraitBorder = new Sprite(); portraitBorder.graphics.lineStyle(1, 0xFFFFFF); portraitBorder.graphics.drawRect(0, 0, primaryTurtlePortrait.width, primaryTurtlePortrait.height); primaryTurtlePortraitContainer = new Sprite(); primaryTurtlePortraitContainer.x = S_PORTRAIT_X_MARGIN; primaryTurtlePortraitContainer.y = S_PORTRAIT_Y_MARGIN; primaryTurtlePortraitContainer.addChild(primaryTurtlePortrait); primaryTurtlePortraitContainer.addChild(portraitBorder); addChild(primaryTurtlePortraitContainer); }; var selectedSecondaryTurtle:String = a_secondaryCharacter; m_activeStatusBox = new ActiveStatusBox(s_statusBoxWidth, (primaryTurtlePortraitContainer.height - 1)); m_activeStatusBox.x = ((primaryTurtlePortraitContainer.x + primaryTurtlePortraitContainer.width) - 1); m_activeStatusBox.y = S_PORTRAIT_Y_MARGIN; addChild(m_activeStatusBox); var secondaryTurtlePortrait:DisplayObject; if (selectedSecondaryTurtle != ""){ portraitClass = m_portraitDict[selectedSecondaryTurtle.toLowerCase()]; secondaryTurtlePortrait = (new (portraitClass) as DisplayObject); portraitBorder = new Sprite(); portraitBorder.graphics.lineStyle(1, 0xFFFFFF); portraitBorder.graphics.drawRect(0, 0, secondaryTurtlePortrait.width, secondaryTurtlePortrait.height); m_secondaryTurtlePortraitContainer = new Sprite(); m_secondaryTurtlePortraitContainer.x = ((primaryTurtlePortraitContainer.x + primaryTurtlePortraitContainer.width) + s_statusBoxWidth); m_secondaryTurtlePortraitContainer.y = S_PORTRAIT_Y_MARGIN; m_secondaryTurtlePortraitContainer.addChild(secondaryTurtlePortrait); m_secondaryTurtlePortraitContainer.addChild(portraitBorder); addChild(m_secondaryTurtlePortraitContainer); }; m_specialAttackOozeCost = Gameplay.calculateOozeRequired(a_secondaryCharacter); m_inActiveStatusBox = new InActiveStatusBox(s_statusBoxWidth, (m_secondaryTurtlePortraitContainer.height - 1), m_specialAttackOozeCost); m_inActiveStatusBox.x = ((m_secondaryTurtlePortraitContainer.x + m_secondaryTurtlePortraitContainer.width) - 1); m_inActiveStatusBox.y = S_PORTRAIT_Y_MARGIN; addChild(m_inActiveStatusBox); dimSecondaryPortrait(); m_comboContainer = new ComboContainer(); addChild(m_comboContainer); m_comboContainer.x = ((Constants.RENDER_WIDTH / 2) - (m_comboContainer.width / 2)); m_comboContainer.visible = false; } public function updateCombo(a_combo:int, a_comboTimer:Number):void{ var percentLeft:Number; if ((((a_combo == 0)) || ((a_comboTimer < 0)))){ Tweener.removeTweens(m_comboContainer); m_comboContainer.visible = false; return; }; m_comboContainer.visible = true; m_comboContainer.updateCombo(a_combo); var timerThird:Number = (Constants.COMBO_TIMER / 3); if (a_comboTimer > timerThird){ m_comboContainer.alpha = 1; } else { percentLeft = (a_comboTimer / timerThird); m_comboContainer.alpha = percentLeft; }; } private function clickMenu(a_mouseEvent:MouseEvent):void{ m_game.showOptions(); } public function update():void{ } public function setScore(a_score:int):void{ m_scoreText.text = ("Score: " + StringUtils.convertToCurrency(a_score)); } public function setOozeRemaining(a_oozeRemaining:int):void{ if (a_oozeRemaining != m_lastOoze){ m_inActiveStatusBox.setOoze(a_oozeRemaining); if (a_oozeRemaining < m_specialAttackOozeCost){ dimSecondaryPortrait(); } else { m_secondaryTurtlePortraitContainer.filters = []; }; }; m_lastOoze = a_oozeRemaining; } public function dispose():void{ m_game = null; } public function clickBack(a_event:Event):void{ m_game.close(); } public function dimSecondaryPortrait():void{ m_secondaryTurtlePortraitContainer.filters = [new ColorMatrixFilter([0.212671, 0.71516, 0.072169, 0, 0, 0.212671, 0.71516, 0.072169, 0, 0, 0.212671, 0.71516, 0.072169, 0, 0, 0, 0, 0, 1, 0])]; } private function clickRestart(a_event:Event):void{ m_game.restartLevel(); } public function setHealthRemaining(a_healthRemaining:int):void{ if (a_healthRemaining != m_lastHealth){ m_activeStatusBox.setHealth(a_healthRemaining); }; m_lastHealth = a_healthRemaining; } } }//package game
Section 243
//Gameplay (game.Gameplay) package game { import shared.*; import com.urbansquall.prophet.engine.*; public class Gameplay { public function Gameplay(){ super(); } public static function hurtPlayer(a_player:Entity, a_amount:int, a_oozeReward:int=1):void{ if (a_player.id != "my_player"){ throw (new Error("This function works on the player only.")); }; a_player.properties.setInt("health", (a_player.properties.getInt("health", Constants.STARTING_HEALTH) - a_amount)); var oozeAmount:int = a_player.properties.getInt("ooze", Constants.STARTING_CHARGE); oozeAmount = (oozeAmount + a_oozeReward); if (oozeAmount >= Constants.STARTING_CHARGE){ oozeAmount = Constants.STARTING_CHARGE; }; a_player.properties.setInt("ooze", oozeAmount); } public static function healPlayer(a_player:Entity, a_amount:int):void{ var newHealth:int = a_player.properties.getInt("health", Constants.STARTING_HEALTH); newHealth = (newHealth + a_amount); if (newHealth > Constants.STARTING_HEALTH){ newHealth = Constants.STARTING_HEALTH; }; a_player.properties.setInt("health", newHealth); } public static function calculateOozeRequired(a_secondaryCharacter:String):int{ var oozeUsage:int; switch (a_secondaryCharacter){ case Constants.CHARACTER_RAPHAEL: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_RAPHAEL; break; case Constants.CHARACTER_CASEY_JONES: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_CASEY_JONES; break; case Constants.CHARACTER_MICHELANGELO: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_MICHELANGELO; break; case Constants.CHARACTER_LEONARDO: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_LEONARDO; break; case Constants.CHARACTER_DONATELLO: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_DONATELLO; break; case Constants.CHARACTER_SPLINTER: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_SPLINTER; break; case Constants.CHARACTER_PIZZA_DUDE: oozeUsage = Constants.CHARACTER_SPECIAL_USAGE_PIZZA_DUDE; break; }; return (oozeUsage); } } }//package game
Section 244
//LevelXMLs (game.LevelXMLs) package game { import flash.utils.*; public class LevelXMLs { public static const LEVEL10:Class = LevelXMLs_LEVEL10; public static const LEVEL11:Class = LevelXMLs_LEVEL11; public static const LEVEL12:Class = LevelXMLs_LEVEL12; public static const LEVEL14:Class = LevelXMLs_LEVEL14; public static const LEVEL16:Class = LevelXMLs_LEVEL16; public static const LEVEL1:Class = LevelXMLs_LEVEL1; public static const LEVEL2:Class = LevelXMLs_LEVEL2; public static const LEVEL3:Class = LevelXMLs_LEVEL3; public static const LEVEL4:Class = LevelXMLs_LEVEL4; public static const LEVEL5:Class = LevelXMLs_LEVEL5; public static const LEVEL6:Class = LevelXMLs_LEVEL6; public static const LEVEL7:Class = LevelXMLs_LEVEL7; public static const LEVEL8:Class = LevelXMLs_LEVEL8; public static const LEVEL9:Class = LevelXMLs_LEVEL9; public static const LEVEL15:Class = LevelXMLs_LEVEL15; public static const LEVEL13:Class = LevelXMLs_LEVEL13; public function LevelXMLs(){ super(); } public static function parseXML(a_contentClass:Class):XML{ var ba:ByteArray; var s:String; var a_contentClass = a_contentClass; ba = (new (a_contentClass) as ByteArray); s = ba.readUTFBytes(ba.length); //unresolved jump var _slot1 = e; throw (new Error(((("Error while parsing XML in LevelXMLs " + _slot1) + " - ") + a_contentClass))); if (s.charCodeAt(0) == 65279){ s = s.slice(1, s.length); }; return (new XML(s)); } } }//package game
Section 245
//LevelXMLs_LEVEL1 (game.LevelXMLs_LEVEL1) package game { import mx.core.*; public class LevelXMLs_LEVEL1 extends ByteArrayAsset { } }//package game
Section 246
//LevelXMLs_LEVEL10 (game.LevelXMLs_LEVEL10) package game { import mx.core.*; public class LevelXMLs_LEVEL10 extends ByteArrayAsset { } }//package game
Section 247
//LevelXMLs_LEVEL11 (game.LevelXMLs_LEVEL11) package game { import mx.core.*; public class LevelXMLs_LEVEL11 extends ByteArrayAsset { } }//package game
Section 248
//LevelXMLs_LEVEL12 (game.LevelXMLs_LEVEL12) package game { import mx.core.*; public class LevelXMLs_LEVEL12 extends ByteArrayAsset { } }//package game
Section 249
//LevelXMLs_LEVEL13 (game.LevelXMLs_LEVEL13) package game { import mx.core.*; public class LevelXMLs_LEVEL13 extends ByteArrayAsset { } }//package game
Section 250
//LevelXMLs_LEVEL14 (game.LevelXMLs_LEVEL14) package game { import mx.core.*; public class LevelXMLs_LEVEL14 extends ByteArrayAsset { } }//package game
Section 251
//LevelXMLs_LEVEL15 (game.LevelXMLs_LEVEL15) package game { import mx.core.*; public class LevelXMLs_LEVEL15 extends ByteArrayAsset { } }//package game
Section 252
//LevelXMLs_LEVEL16 (game.LevelXMLs_LEVEL16) package game { import mx.core.*; public class LevelXMLs_LEVEL16 extends ByteArrayAsset { } }//package game
Section 253
//LevelXMLs_LEVEL2 (game.LevelXMLs_LEVEL2) package game { import mx.core.*; public class LevelXMLs_LEVEL2 extends ByteArrayAsset { } }//package game
Section 254
//LevelXMLs_LEVEL3 (game.LevelXMLs_LEVEL3) package game { import mx.core.*; public class LevelXMLs_LEVEL3 extends ByteArrayAsset { } }//package game
Section 255
//LevelXMLs_LEVEL4 (game.LevelXMLs_LEVEL4) package game { import mx.core.*; public class LevelXMLs_LEVEL4 extends ByteArrayAsset { } }//package game
Section 256
//LevelXMLs_LEVEL5 (game.LevelXMLs_LEVEL5) package game { import mx.core.*; public class LevelXMLs_LEVEL5 extends ByteArrayAsset { } }//package game
Section 257
//LevelXMLs_LEVEL6 (game.LevelXMLs_LEVEL6) package game { import mx.core.*; public class LevelXMLs_LEVEL6 extends ByteArrayAsset { } }//package game
Section 258
//LevelXMLs_LEVEL7 (game.LevelXMLs_LEVEL7) package game { import mx.core.*; public class LevelXMLs_LEVEL7 extends ByteArrayAsset { } }//package game
Section 259
//LevelXMLs_LEVEL8 (game.LevelXMLs_LEVEL8) package game { import mx.core.*; public class LevelXMLs_LEVEL8 extends ByteArrayAsset { } }//package game
Section 260
//LevelXMLs_LEVEL9 (game.LevelXMLs_LEVEL9) package game { import mx.core.*; public class LevelXMLs_LEVEL9 extends ByteArrayAsset { } }//package game
Section 261
//PlayerStateMachine (game.PlayerStateMachine) package game { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import caurina.transitions.*; import com.urbansquall.audio.*; import flash.media.*; import com.urbansquall.prophet.input.*; import Box2D.Collision.Shapes.*; public class PlayerStateMachine { private var m_dieSound:Sound;// = null private var m_safePositions:Array; private var m_blockRightTime:int; private var m_currentState:Function; private var m_jumpSound:Sound;// = null private var m_wallJumpEnabled:Boolean; private var m_inWallGracePeriod:Boolean;// = false private var m_wasCrouchCharged:Boolean; private var m_wallSlideSoundChannel:SoundChannel;// = null private var m_interval:Number; private var m_keyboard:KeyboardState; private var m_wallSlideSound:Sound;// = null private var m_animator:AnimationPlayer; private var m_lockMovement:Boolean; private var m_bladeWeaponSound:Sound;// = null private var m_bluntWeaponSound:Sound;// = null private var m_blockLeftTime:int; private var m_comboContinues:Boolean; private var m_attackRects:PlayerAttackBoxes; private var m_wallReleaseGraceTime:int; private var m_player:Entity; private var m_moveState:Function; private static const DOUBLE_JUMP_VELOCITY:int = -294; private static const WALL_RELEASE_GRACE_TIME:int = 600; private static const WALL_SLIDE_SPEED:int = 70; private static const MAX_HORIZONTAL_SPEED:int = 130; private static const WALL_INPUT_BLOCK_TIME:int = 530; public static const PLAYER_DENSITY:Number = 5.6; private static const WALL_SLIDE_LOOP_ID:String = "wallSlideLoopId"; private static const MOVEMENT_RATE:Number = 2.8; private static const WALL_JUMP_Y_VEL:int = -300; private static const JUMP_VELOCITY:int = -320; private static const WALL_JUMP_X_VEL:int = 150; public function PlayerStateMachine(a_player:Entity, a_keyboardState:KeyboardState, a_wallJumpEnabled:Boolean){ var leoAttacks:PlayerAttackBoxes; var raphAttacks:PlayerAttackBoxes; var donAttacks:PlayerAttackBoxes; var mikeAttacks:PlayerAttackBoxes; m_safePositions = []; super(); m_wallJumpEnabled = a_wallJumpEnabled; m_player = a_player; m_keyboard = a_keyboardState; m_currentState = idleState; m_moveState = standingState; m_blockLeftTime = 0; m_blockRightTime = 0; m_wallReleaseGraceTime = 0; m_lockMovement = false; m_comboContinues = false; m_dieSound = new TurtleDie(); m_jumpSound = new SmallJumpNoise1(); m_bladeWeaponSound = new BladeSwipeNoise1(); m_bluntWeaponSound = new BluntSwingNoise1(); m_wallSlideSound = new WallSlide(); m_animator = (m_player.lookupGraphic("image") as GingerGraphic).animationPlayer; if (m_player.type == Constants.ENTITY_TYPE_LEONARDO){ leoAttacks = new PlayerAttackBoxes(); leoAttacks.combo1 = new Rectangle(10, -20, 46, 28); leoAttacks.combo2 = new Rectangle(10, -28, 42, 36); leoAttacks.combo3 = new Rectangle(10, -26, 54, 28); leoAttacks.air = new Rectangle(10, -28, 46, 28); leoAttacks.crouch = new Rectangle(10, 0, 43, 38); m_attackRects = leoAttacks; } else { if (m_player.type == Constants.ENTITY_TYPE_RAPHAEL){ raphAttacks = new PlayerAttackBoxes(); raphAttacks.combo1 = new Rectangle(10, -20, 40, 28); raphAttacks.combo2 = new Rectangle(10, -28, 38, 36); raphAttacks.combo3 = new Rectangle(10, -26, 44, 28); raphAttacks.air = new Rectangle(10, -28, 40, 28); raphAttacks.crouch = new Rectangle(10, -10, 38, 48); m_attackRects = raphAttacks; } else { if (m_player.type == Constants.ENTITY_TYPE_DONATELLO){ donAttacks = new PlayerAttackBoxes(); donAttacks.combo1 = new Rectangle(10, -20, 52, 28); donAttacks.combo2 = new Rectangle(10, -28, 42, 36); donAttacks.combo3 = new Rectangle(10, -26, 54, 28); donAttacks.air = new Rectangle(10, -32, 46, 32); donAttacks.crouch = new Rectangle(10, -20, 49, 58); m_attackRects = donAttacks; } else { if (m_player.type == Constants.ENTITY_TYPE_MICHELANGELO){ mikeAttacks = new PlayerAttackBoxes(); mikeAttacks.combo1 = new Rectangle(10, -20, 44, 28); mikeAttacks.combo2 = new Rectangle(10, -28, 38, 36); mikeAttacks.combo3 = new Rectangle(10, -26, 44, 28); mikeAttacks.air = new Rectangle(10, -28, 40, 28); mikeAttacks.crouch = new Rectangle(10, -10, 38, 48); m_attackRects = mikeAttacks; }; }; }; }; } private function jumpState():void{ m_wallReleaseGraceTime = -1; if (m_player.getVelocity().y > 0){ changeState(fallingState); return; }; if (manageAirOptions()){ return; }; if (m_player.properties.getBoolean("hasDoubleJumped", false)){ play("falling"); } else { play("jumping"); }; } private function onCombo1GraceChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo1GraceChange); manageComboContinuing(); }; } private function idleToCrouchState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "crouchtransition"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onIdleToCrouchChange); play("crouchtransition"); } private function crouchAttackState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "crouchattackDelay"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onCrouchAttackDelayChange); m_wasCrouchCharged = true; play("crouchattackDelay"); } private function processInvulnerability():void{ var s:b2Shape; var filterData:b2FilterData; var currTimer:Number = m_player.properties.getNumber("invincibleTimer", 0); var newTimer:Number = (currTimer - m_interval); if (newTimer > 0){ m_player.properties.setNumber("invincibleTimer", newTimer); m_animator.transform.colorTransform = new ColorTransform(1.2, 1.2, 1.2); m_animator.alpha = (0.4 + (0.6 * ((newTimer % 200) / 200))); if (m_player.properties.getInt("activeGroupIndex", 0) != Constants.ENEMY_GROUP_FILTER){ s = m_player.body.GetShapeList(); while (s) { filterData = s.GetFilterData(); filterData.groupIndex = Constants.ENEMY_GROUP_FILTER; s.SetFilterData(filterData); m_player.getEngine().getDynamics().refilter(s); s = s.GetNext(); }; m_player.properties.setInt("activeGroupIndex", Constants.ENEMY_GROUP_FILTER); }; } else { if (currTimer > 0){ cancelInvincibility(); }; }; } private function startSpecial():Boolean{ var invincibleTimer:Number; var secondaryCharacter:String = m_player.properties.getString(Constants.DATA_SELECTED_SECONDARY, Constants.CHARACTER_PIZZA_DUDE); var oozeRequired:int = Gameplay.calculateOozeRequired(secondaryCharacter); if (m_player.properties.getInt("ooze", 0) >= oozeRequired){ invincibleTimer = 950; if ((((secondaryCharacter == Constants.CHARACTER_DONATELLO)) || ((secondaryCharacter == Constants.CHARACTER_LEONARDO)))){ invincibleTimer = 800; }; if (secondaryCharacter == Constants.CHARACTER_SPLINTER){ invincibleTimer = 1200; }; m_player.properties.setNumber("invincibleTimer", invincibleTimer); changeState(specialState); return (true); } else { SoundSystem.instance.playSound(new Buzz(), 0.7); }; return (false); } private function idleState():void{ var groundNormal:Point; if (m_player.properties.getBoolean("standingOnSomething", true)){ m_player.properties.setBoolean("hasDoubleJumped", false); m_player.properties.setBoolean("canShellAttack", true); }; if (!m_player.properties.getBoolean("standingOnSomething", true)){ changeState(fallingState); return; }; if (((m_keyboard.wasJustPressed(KeyboardMap.UP)) || (m_keyboard.wasJustPressed(KeyboardMap.SPACE)))){ m_player.body.SetLinearDamping(0); changeState(idleToJumpState); return; }; if (m_keyboard.isDown(KeyboardMap.DOWN)){ changeState(idleToCrouchState); return; }; if (m_keyboard.wasJustPressed(KeyboardMap.A)){ changeState(combo1State); return; }; if (m_keyboard.wasJustPressed(KeyboardMap.S)){ if (startSpecial()){ return; }; }; m_player.body.SetLinearDamping(0); if (m_player.properties.getBoolean("standingOnSomething", true)){ groundNormal = new Point(m_player.properties.getNumber("groundNormalX", 0), m_player.properties.getNumber("groundNormalY", -1)); groundNormal.normalize(1); if ((((groundNormal.y > -1)) && ((groundNormal.y < -0.5)))){ if (m_moveState == standingState){ m_player.setVelocity(0, 0); m_player.body.SetLinearDamping(100); }; }; }; if (m_moveState != standingState){ play("walk"); } else { play("idle"); }; } private function wallSlideGraceState():void{ var rightWall:Boolean; if (m_wallReleaseGraceTime <= 0){ m_wallReleaseGraceTime = WALL_RELEASE_GRACE_TIME; } else { m_wallReleaseGraceTime = (m_wallReleaseGraceTime - m_interval); }; if (((!(m_player.properties.getBoolean("touchingWall", false))) || (m_player.properties.getBoolean("standingOnSomething", false)))){ changeState(fallingState); return; }; if (m_wallReleaseGraceTime <= 0){ if (m_player.properties.getBoolean("standingOnSomething", false)){ changeState(idleState); return; }; if (!isInteractingWithWall()){ changeState(fallingState); return; }; stopWallSlideSound(); } else { if (checkForWallJump()){ stopWallSlideSound(); return; }; rightWall = m_player.properties.getBoolean("rightWall", false); if (((((rightWall) && (m_keyboard.isDown(KeyboardMap.LEFT)))) || (((!(rightWall)) && (m_keyboard.isDown(KeyboardMap.RIGHT)))))){ stopWallSlideSound(); changeState(fallingState); return; }; }; m_player.setVelocity(m_player.getVelocity().x, WALL_SLIDE_SPEED); play("wallslide"); playWallSlideSound(); } private function actualCrouchAttackState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "crouchattack"){ return; }; m_animator.addEventListener(FrameEvent.CHANGE, onCrouchAttackFrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onCrouchAttackChange); play("crouchattack"); } private function onShellRotateChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onShellRotateChange); m_player.properties.setBoolean("shellAttacking", true); changeState(shellAttackState); }; } private function combo3State():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo3"){ return; }; m_animator.addEventListener(FrameEvent.CHANGE, onCombo3FrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onCombo3Change); play("combo3"); } private function onCrouchAttackChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCrouchAttackChange); changeState(crouchState); }; } private function isInteractingWithWall():Boolean{ if ((((m_blockLeftTime > 0)) || ((m_blockRightTime > 0)))){ return (false); }; return (((m_player.properties.getBoolean("touchingWall", false)) && (((((m_keyboard.isDown(KeyboardMap.RIGHT)) && (m_player.properties.getBoolean("rightWall", false)))) || (((m_keyboard.isDown(KeyboardMap.LEFT)) && (!(m_player.properties.getBoolean("rightWall", false))))))))); } private function play(a_animationId:String, a_doNotRestart:Boolean=true):void{ if (((a_doNotRestart) && ((m_animator.currentAnimationID == a_animationId)))){ return; }; m_animator.play(a_animationId); } private function onSpecialChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onSpecialChange); changeState(idleState); }; } private function combo2GraceState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo2Grace"){ if (m_keyboard.wasJustPressed(KeyboardMap.A)){ m_comboContinues = true; }; return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onCombo2GraceChange); play("combo2Grace"); } private function manageAirOptions():Boolean{ if (m_keyboard.wasJustPressed(KeyboardMap.A)){ if (((m_keyboard.isDown(KeyboardMap.DOWN)) && (m_player.properties.getBoolean("canShellAttack", true)))){ changeState(shellRotateState); } else { changeState(airAttackState); }; return (true); } else { if (m_keyboard.wasJustPressed(KeyboardMap.S)){ return (startSpecial()); }; if (((((((((m_keyboard.wasJustPressed(KeyboardMap.UP)) || (m_keyboard.wasJustPressed(KeyboardMap.SPACE)))) && (!(m_player.properties.getBoolean("hasDoubleJumped", false))))) && ((m_blockLeftTime <= 0)))) && ((m_blockRightTime <= 0)))){ m_player.properties.setBoolean("hasDoubleJumped", true); changeState(idleToJumpState); return (true); }; if ((((((m_animator.currentAnimationID == "falling")) || ((m_animator.currentAnimationID == "jumping")))) && (m_player.properties.getBoolean("standingOnSomething", false)))){ if (m_player.properties.getNumber("timeOfStandingOnSomething", 0) > 66){ changeState(idleState); return (true); }; }; }; return (false); } private function onCrouchAttackDelayChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCrouchAttackDelayChange); changeState(actualCrouchAttackState); }; } private function attack(a_rectangle:Rectangle, a_hasKnockback:Boolean=false, a_halfDamage:Boolean=false):void{ var hitEntity:Entity; var container:DisplayObjectContainer; var playerPosition:Point = m_player.getPosition(); var startX:Number = (playerPosition.x + a_rectangle.x); var startY:Number = (playerPosition.y + a_rectangle.y); var horizontalOffset:Number = (0.8 * a_rectangle.width); if (m_player.flipped){ startX = ((playerPosition.x - a_rectangle.x) - a_rectangle.width); horizontalOffset = (a_rectangle.width - horizontalOffset); }; var boxedEntities:Array = m_player.getEngine().queryBox(startX, startY, a_rectangle.width, a_rectangle.height, true); var b:int; while (b < boxedEntities.length) { hitEntity = boxedEntities[b]; if (hitEntity != m_player){ if (!hitEntity.properties.getBoolean("isEnemy", false)){ } else { if (hitEntity.properties.getInt("lives", 1) <= 0){ } else { container = m_player.getEngine().renderer.lookupRenderLayer((Constants.ENTITY_DEFAULT_RENDER_LAYER + 10)); Effects.drawTurtleAttackEffect((startX + horizontalOffset), (startY + (a_rectangle.height / 2)), container, 10); AttackManager.turtleAttack(m_player, hitEntity, a_hasKnockback, a_halfDamage); }; }; }; b++; }; playWeaponSound(); } private function fallingState():void{ if (m_player.properties.getBoolean("standingOnSomething", false)){ changeState(idleState); return; }; if (((m_wallJumpEnabled) && (isInteractingWithWall()))){ changeState(wallSlideState); return; }; if (manageAirOptions()){ return; }; play("falling"); } private function onIdleToJumpChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onIdleToJumpChange); changeState(jumpState); }; } private function onIdleToCrouchChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onIdleToCrouchChange); changeState(crouchState); }; } private function onCombo2FrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; m_animator.removeEventListener(FrameEvent.CHANGE, onCombo2FrameChange); attack(m_attackRects.combo2); } private function idleToJumpState():void{ if (m_animator.currentAnimationID == "jumpingtransition"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onIdleToJumpChange); SoundSystem.instance.playSound(m_jumpSound); play("jumpingtransition"); var jumpVelocity:Number = JUMP_VELOCITY; if (m_player.properties.getBoolean("hasDoubleJumped", false)){ jumpVelocity = DOUBLE_JUMP_VELOCITY; }; drawJumpDust("jump_dust"); m_player.setVelocity(m_player.getVelocity().x, jumpVelocity); } public function get safePositions():Array{ return (m_safePositions); } private function onFlinchChange(a_event:AnimationEvent):void{ if ((((a_event.animationID.indexOf("flinch") >= 0)) && (!(a_event.begin)))){ m_animator.removeEventListener(AnimationEvent.CHANGE, onFlinchChange); m_player.properties.setBoolean("isFlinching", false); m_player.properties.setInt("flinchingDir", 0); changeState(idleState); }; } private function flinchState():void{ m_lockMovement = true; if ((((m_animator.currentAnimationID == "groundflinch")) || ((m_animator.currentAnimationID == "airflinch")))){ return; }; var xKnock:Number = 120; if (m_player.properties.getInt("flinchingDir", -1) < 0){ xKnock = -(xKnock); }; m_player.setVelocity(xKnock, -170); m_animator.addEventListener(AnimationEvent.CHANGE, onFlinchChange); if (m_player.properties.getBoolean("standingOnSomething", true)){ play("groundflinch"); } else { play("airflinch"); }; SoundSystem.instance.playSound(new TurtleHitGrunt1()); } private function drawJumpDust(a_type:String):void{ var jumpDust:AnimationPlayer; jumpDust = GingerFactory.getInstance().instantiate(a_type); jumpDust.startSelfTick(33); jumpDust.x = m_player.getPosition().x; jumpDust.y = m_player.getPosition().y; Tweener.addTween(jumpDust, {alpha:0, delay:0.4, time:0.3, onComplete:m_player.getEngine().renderer.removeDisplayObject, onCompleteParams:[jumpDust]}); m_player.getEngine().renderer.addDisplayObject(jumpDust, (Constants.ENTITY_DEFAULT_RENDER_LAYER - 1)); } private function onCombo2GraceChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo2GraceChange); manageComboContinuing(); }; } private function specialState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "special"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onSpecialChange); SoundSystem.instance.playSound(new SpecialAttackActivationNoise1()); play("special"); SpecialAttack.fire(m_player); } private function onAirAttackFrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; m_animator.removeEventListener(FrameEvent.CHANGE, onAirAttackFrameChange); attack(m_attackRects.air); } private function changeMoveState(a_stateFunc:Function):void{ m_moveState = a_stateFunc; m_moveState(); } private function onCombo1Change(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo1Change); manageComboContinuing(); }; } private function deathState():void{ m_lockMovement = true; m_animator.addEventListener(AnimationEvent.CHANGE, onDeathChange); m_animator.defaultAnimationID = "death"; play("death"); } private function airAttackState():void{ if (m_animator.currentAnimationID == "airattack"){ return; }; m_animator.addEventListener(FrameEvent.CHANGE, onAirAttackFrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onAirAttackChange); play("airattack"); } private function combo1GraceState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo1Grace"){ if (m_keyboard.wasJustPressed(KeyboardMap.A)){ m_comboContinues = true; }; return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onCombo1GraceChange); play("combo1Grace"); } private function moveRightState():void{ var nextState:Function; if (m_blockRightTime > 0){ return; }; if (!m_keyboard.isDown(KeyboardMap.RIGHT)){ nextState = standingState; if (m_keyboard.isDown(KeyboardMap.LEFT)){ nextState = moveLeftState; }; changeMoveState(nextState); return; } else { if (m_keyboard.wasJustPressed(KeyboardMap.LEFT)){ changeMoveState(moveLeftState); return; }; }; m_player.flip = false; if (m_player.getVelocity().x < MAX_HORIZONTAL_SPEED){ m_player.applyImpulse((PLAYER_DENSITY * MOVEMENT_RATE), 0); }; } private function combo2State():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo2"){ if (m_keyboard.wasJustPressed(KeyboardMap.A)){ m_comboContinues = true; }; return; }; m_animator.addEventListener(FrameEvent.CHANGE, onCombo2FrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onCombo2Change); play("combo2"); } private function playWeaponSound():void{ var weaponSound:Sound; switch (m_player.type){ case Constants.ENTITY_TYPE_LEONARDO: case Constants.ENTITY_TYPE_RAPHAEL: weaponSound = m_bladeWeaponSound; break; case Constants.ENTITY_TYPE_MICHELANGELO: case Constants.ENTITY_TYPE_DONATELLO: weaponSound = m_bluntWeaponSound; break; default: trace("unidentified entity in PlayerStateMachine.as, proceeding as if its Leo"); weaponSound = m_bladeWeaponSound; break; }; SoundSystem.instance.playSound(weaponSound); } private function onCrouchAttackFrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; m_animator.removeEventListener(FrameEvent.CHANGE, onCrouchAttackFrameChange); attack(m_attackRects.crouch, true, !(m_wasCrouchCharged)); m_wasCrouchCharged = false; } private function wallSlideSoundComplete(a_event:Event):void{ m_wallSlideSoundChannel = null; } private function onAirAttackChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onAirAttackChange); if (m_player.getVelocity().y > 0){ changeState(fallingState); } else { if (m_player.getVelocity().y < 0){ changeState(jumpState); } else { changeState(idleState); }; }; }; } private function standingState():void{ if (m_keyboard.isDown(KeyboardMap.RIGHT)){ m_player.body.SetLinearDamping(0); changeMoveState(moveRightState); return; }; if (m_keyboard.isDown(KeyboardMap.LEFT)){ m_player.body.SetLinearDamping(0); changeMoveState(moveLeftState); return; }; } private function shellRotateState():void{ if (m_player.properties.getNumber("invincibleTimer", 0) > 0){ m_player.properties.setBoolean("canShellAttack", false); changeState(fallingState); return; }; m_lockMovement = true; m_player.setVelocity(0, 0); if (m_animator.currentAnimationID == "shellrotate"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onShellRotateChange); play("shellrotate"); } private function playWallSlideSound():void{ if (m_wallSlideSoundChannel == null){ m_wallSlideSoundChannel = SoundSystem.instance.playSound(this.m_wallSlideSound, 1, wallSlideSoundComplete); }; } private function onCombo2Change(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo2Change); manageComboContinuing(); }; } private function onCombo3FrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; m_animator.removeEventListener(FrameEvent.CHANGE, onCombo3FrameChange); attack(m_attackRects.combo3, true); } private function manageComboContinuing():void{ var nextComboState:Function; var nextIdleState:Function; var doesComboContinue:Boolean = m_comboContinues; m_comboContinues = false; if (doesComboContinue){ if (m_keyboard.isDown(KeyboardMap.LEFT)){ m_player.flip = true; } else { if (m_keyboard.isDown(KeyboardMap.RIGHT)){ m_player.flip = false; }; }; if (m_keyboard.isDown(KeyboardMap.DOWN)){ changeState(crouchAttackState); } else { nextComboState = combo2State; if ((((m_currentState == combo2State)) || ((m_currentState == combo2GraceState)))){ nextComboState = combo3State; }; changeState(nextComboState); }; } else { nextIdleState = combo1GraceState; if (m_currentState == combo2State){ nextIdleState = combo2GraceState; } else { if ((((m_currentState == combo1GraceState)) || ((m_currentState == combo2GraceState)))){ nextIdleState = idleState; }; }; changeState(nextIdleState); }; } private function changeState(a_stateFunc:Function, a_doChangeNow:Boolean=true):void{ m_currentState = a_stateFunc; if (a_doChangeNow){ m_currentState(); }; } private function onCombo3GraceChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo3GraceChange); changeState(idleState); }; } private function onAnythingToDeathChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onAnythingToDeathChange); changeState(deathState); }; } public function update(a_interval:Number):void{ var standingOnID:String; var recordSafePosition:Boolean; var standingOnEntity:Entity; var newSafePosition:Point; var lastSafePosition:Point; var displacement:Point; if (m_animator.currentAnimationID == "dead"){ return; }; m_interval = a_interval; if (((!((m_animator.currentAnimationID == "wallslide"))) && (m_player.properties.getBoolean("standingOnSomething", true)))){ standingOnID = m_player.properties.getString("standingOnID", ""); recordSafePosition = true; standingOnEntity = m_player.getEngine().lookupEntity(standingOnID); if (standingOnEntity != null){ if (!standingOnEntity.properties.getBoolean("safeToRespawnTo", true)){ recordSafePosition = false; }; }; if (recordSafePosition){ newSafePosition = new Point(m_player.getPosition().x, m_player.getPosition().y); if (m_safePositions.length == 0){ m_safePositions.push(newSafePosition); }; lastSafePosition = m_safePositions[(m_safePositions.length - 1)]; displacement = newSafePosition.subtract(lastSafePosition); if (displacement.length > 15){ m_player.properties.setInt("lastSafeX", newSafePosition.x); m_player.properties.setInt("lastSafeY", newSafePosition.y); m_safePositions.push(newSafePosition); if (m_safePositions.length >= 30){ m_safePositions.splice(0, 1); }; }; }; }; if (m_blockLeftTime > 0){ m_blockLeftTime = (m_blockLeftTime - a_interval); }; if (m_blockRightTime > 0){ m_blockRightTime = (m_blockRightTime - a_interval); }; if (m_player.properties.getInt("health", Constants.STARTING_HEALTH) <= 0){ if (m_currentState != deathState){ changeState(anythingToDeathState, false); }; } else { if (m_player.properties.getBoolean("isFlinching", false)){ changeState(flinchState, false); }; }; m_lockMovement = false; m_currentState(); if ((((((m_blockLeftTime <= 0)) && ((m_blockRightTime <= 0)))) && ((m_player.properties.getInt("flinchingDir", 0) == 0)))){ m_player.setVelocity(0, m_player.getVelocity().y); }; if (!m_lockMovement){ m_moveState(); }; processInvulnerability(); } private function shellExitState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "shellexit"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onShellExitChange); play("shellexit"); } private function wallSlideState():void{ var rightWall:Boolean; if (m_player.properties.getBoolean("standingOnSomething", false)){ changeState(idleState); return; }; if (!isInteractingWithWall()){ rightWall = m_player.properties.getBoolean("rightWall", false); if (((((rightWall) && (m_keyboard.isDown(KeyboardMap.LEFT)))) || (((!(rightWall)) && (m_keyboard.isDown(KeyboardMap.RIGHT)))))){ stopWallSlideSound(); changeState(fallingState); } else { if (((((((rightWall) && (m_keyboard.isDown(KeyboardMap.RIGHT)))) && ((m_moveState == moveRightState)))) || (((((!(rightWall)) && (m_keyboard.isDown(KeyboardMap.LEFT)))) && ((m_moveState == moveLeftState)))))){ stopWallSlideSound(); changeState(fallingState); } else { changeState(wallSlideGraceState); }; }; return; } else { if (checkForWallJump()){ return; }; }; m_player.setVelocity(m_player.getVelocity().x, WALL_SLIDE_SPEED); play("wallslide"); playWallSlideSound(); } private function shellAttackState():void{ if (m_player.properties.getNumber("invincibleTimer", 0) > 0){ m_player.properties.setBoolean("canShellAttack", false); changeState(fallingState); return; }; if (!m_player.properties.getBoolean("shellAttacking", true)){ changeState(jumpState); return; }; m_lockMovement = true; if (m_player.properties.getBoolean("standingOnSomething", false)){ changeState(shellExitState); return; }; m_player.setVelocity(0, 500); play("shellattack"); m_player.properties.setBoolean("canShellAttack", false); } private function onShellExitChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onShellExitChange); changeState(idleState); }; } private function checkForWallJump():Boolean{ if (((m_keyboard.wasJustPressed(KeyboardMap.UP)) || (m_keyboard.wasJustPressed(KeyboardMap.SPACE)))){ if (m_player.properties.getBoolean("rightWall", false)){ m_blockRightTime = WALL_INPUT_BLOCK_TIME; m_player.flip = true; m_player.setVelocity(-(WALL_JUMP_X_VEL), WALL_JUMP_Y_VEL); } else { m_blockLeftTime = WALL_INPUT_BLOCK_TIME; m_player.flip = false; m_player.setVelocity(WALL_JUMP_X_VEL, WALL_JUMP_Y_VEL); }; changeState(jumpState); return (true); }; return (false); } private function onDeathChange(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onDeathChange); m_player.properties.setBoolean("dead", true); } else { SoundSystem.instance.playSound(m_dieSound); }; } private function stopWallSlideSound():void{ if (m_wallSlideSoundChannel != null){ m_wallSlideSoundChannel.stop(); m_wallSlideSoundChannel = null; }; } private function cancelInvincibility():void{ var s:b2Shape; var filterData:b2FilterData; var regularGroupIndex:int; if (m_player.properties.getInt("activeGroupIndex", 0) == regularGroupIndex){ return; }; m_player.properties.setNumber("invincibleTimer", 0); m_animator.transform.colorTransform = new ColorTransform(); m_animator.alpha = 1; s = m_player.body.GetShapeList(); while (s) { filterData = s.GetFilterData(); filterData.groupIndex = regularGroupIndex; s.SetFilterData(filterData); m_player.getEngine().getDynamics().refilter(s); s = s.GetNext(); }; m_player.properties.setInt("activeGroupIndex", regularGroupIndex); } private function combo1State():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo1"){ if (m_keyboard.wasJustPressed(KeyboardMap.A)){ m_comboContinues = true; }; return; }; m_animator.addEventListener(FrameEvent.CHANGE, onCombo1FrameChange); m_animator.addEventListener(AnimationEvent.CHANGE, onCombo1Change); play("combo1"); } private function onCombo3Change(a_event:AnimationEvent):void{ if (!a_event.begin){ m_animator.removeEventListener(AnimationEvent.CHANGE, onCombo3Change); changeState(combo3GraceState); }; } private function crouchState():void{ if (!m_keyboard.isDown(KeyboardMap.DOWN)){ changeState(idleState); return; }; if (m_keyboard.wasJustPressed(KeyboardMap.A)){ changeState(actualCrouchAttackState); return; }; if (m_keyboard.wasJustPressed(KeyboardMap.S)){ if (startSpecial()){ return; }; }; if (m_keyboard.isDown(KeyboardMap.LEFT)){ m_player.flip = true; } else { if (m_keyboard.isDown(KeyboardMap.RIGHT)){ m_player.flip = false; }; }; m_lockMovement = true; play("crouch"); } private function moveLeftState():void{ var nextState:Function; if (m_blockLeftTime > 0){ return; }; if (!m_keyboard.isDown(KeyboardMap.LEFT)){ nextState = standingState; if (m_keyboard.isDown(KeyboardMap.RIGHT)){ nextState = moveRightState; }; changeMoveState(nextState); return; } else { if (m_keyboard.wasJustPressed(KeyboardMap.RIGHT)){ changeMoveState(moveRightState); return; }; }; m_player.flip = true; if (m_player.getVelocity().x > -(MAX_HORIZONTAL_SPEED)){ m_player.applyImpulse((-(PLAYER_DENSITY) * MOVEMENT_RATE), 0); }; } private function anythingToDeathState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "deathtransition"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onAnythingToDeathChange); play("deathtransition"); } private function onCombo1FrameChange(a_event:FrameEvent):void{ if (a_event.frameID != "attackStart"){ return; }; m_animator.removeEventListener(FrameEvent.CHANGE, onCombo1FrameChange); attack(m_attackRects.combo1); } private function combo3GraceState():void{ m_lockMovement = true; if (m_animator.currentAnimationID == "combo3Grace"){ return; }; m_animator.addEventListener(AnimationEvent.CHANGE, onCombo3GraceChange); play("idle"); } } }//package game
Section 262
//SpecialAttack (game.SpecialAttack) package game { import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import caurina.transitions.*; public class SpecialAttack { public function SpecialAttack(){ super(); } private static function doSplinterAttack(a_player:Entity):void{ var engine:Engine = a_player.getEngine(); var startX:Number = engine.renderer.view.viewX; var startY:Number = engine.renderer.view.viewY; var partner:Entity = engine.createEntity(new EntitySpawnInfo(Constants.ENTITY_TYPE_SPECIAL_SPLINTER, "", startX, startY, 0, 0)); } private static function killDisplayObject(a_displayObject:DisplayObject):void{ a_displayObject.parent.removeChild(a_displayObject); } private static function cleanup(a_display:DisplayObjectContainer):void{ a_display.parent.removeChild(a_display); } public static function fire(a_player:Entity):void{ var secondaryCharacter:String = a_player.properties.getString(Constants.DATA_SELECTED_SECONDARY, Constants.CHARACTER_PIZZA_DUDE); var oozeUsage:int = Gameplay.calculateOozeRequired(secondaryCharacter); var oozeAvailable:int = a_player.properties.getInt("ooze", 0); if (oozeAvailable >= oozeUsage){ switch (secondaryCharacter){ case Constants.CHARACTER_RAPHAEL: fireEntity(a_player, Constants.ENTITY_TYPE_SPECIAL_RAPHAEL); break; case Constants.CHARACTER_CASEY_JONES: fireEntity(a_player, Constants.ENTITY_TYPE_SPECIAL_CASEY_JONES); break; case Constants.CHARACTER_MICHELANGELO: fireEntity(a_player, Constants.ENTITY_TYPE_SPECIAL_MICHELANGELO); break; case Constants.CHARACTER_LEONARDO: doFullScreenAttack(a_player, "humans", 304, secondaryCharacter); break; case Constants.CHARACTER_DONATELLO: doFullScreenAttack(a_player, "robots", 320, secondaryCharacter); break; case Constants.CHARACTER_SPLINTER: doSplinterAttack(a_player); break; case Constants.CHARACTER_PIZZA_DUDE: Gameplay.healPlayer(a_player, 5); fireEntity(a_player, Constants.ENTITY_TYPE_SPECIAL_PIZZA_DELIVERY); break; }; a_player.properties.setInt("ooze", (oozeAvailable - oozeUsage)); }; } private static function fireEntity(a_player:Entity, a_type:String):void{ var engine:Engine = a_player.getEngine(); var startX:Number = (engine.renderer.view.viewX - (Constants.RENDER_WIDTH / 2)); var pos:Point = a_player.getPosition(); var speed:Number = 750; if (a_player.flipped){ speed = (speed * -1); startX = (engine.renderer.view.viewX + (Constants.RENDER_WIDTH / 2)); }; var partner:Entity = engine.createEntity(new EntitySpawnInfo(a_type, "", startX, pos.y, speed, 0)); partner.flip = a_player.flipped; } private static function completeFullScreenAttack(effectContainer:Sprite, a_player:Entity, a_damageType:String, a_damageAmount:int):void{ var entityK:Entity; var flinchDir:int; var engine:Engine = a_player.getEngine(); var viewX:Number = engine.renderer.view.viewX; var viewY:Number = engine.renderer.view.viewY; var boxedEntities:Array = a_player.getEngine().queryBox((viewX - (Constants.RENDER_WIDTH / 2)), (viewY - (Constants.RENDER_HEIGHT / 2)), Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT, true); var k:int; while (k < boxedEntities.length) { entityK = boxedEntities[k]; if (entityK != a_player){ flinchDir = ((entityK.getPosition().x)>a_player.getPosition().x) ? 1 : -1; AttackManager.doTurtleAttack(entityK, a_damageAmount, a_damageType, flinchDir, true); }; k++; }; Tweener.addTween(effectContainer, {alpha:0, time:0.5, onComplete:killDisplayObject, onCompleteParams:[effectContainer]}); flashScreen(viewX, viewY, engine); } private static function flashScreen(a_x:Number, a_y:Number, a_engine:Engine):void{ var debugDraw:Sprite = a_engine.renderer.lookupRenderLayer((Constants.ENTITY_DEFAULT_RENDER_LAYER + 50)); var box:Sprite = new Sprite(); box.graphics.beginFill(0xFFFFFF, 0.5); box.x = (a_x - (Constants.RENDER_WIDTH / 2)); box.y = (a_y - (Constants.RENDER_HEIGHT / 2)); box.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); debugDraw.addChild(box); Tweener.addTween(box, {alpha:0, time:0.5, onComplete:debugDraw.removeChild, onCompleteParams:[box]}); } private static function doFullScreenAttack(a_player:Entity, a_damageType:String, a_damageAmount:int, a_secondaryCharacter:String):void{ var offsetX:int; var offsetY:int; var trail:AnimationPlayer; var effectTime:Number = 0.5; var container:DisplayObjectContainer = (a_player.getEngine().renderer.renderContainer.root as DisplayObjectContainer); var effectContainer:Sprite = new Sprite(); container.addChild(effectContainer); effectContainer.x = (effectContainer.x + (Constants.RENDER_WIDTH / 2)); effectContainer.y = (effectContainer.y + (Constants.RENDER_HEIGHT / 2)); effectContainer.alpha = 0; var tile1:AnimationPlayer = GingerFactory.getInstance().instantiate((a_secondaryCharacter.toLowerCase() + "_tile")); effectContainer.addChild(tile1); tile1.startSelfTick(33); tile1.y = (tile1.y + (tile1.height / 2)); var tile2:AnimationPlayer = GingerFactory.getInstance().instantiate((a_secondaryCharacter.toLowerCase() + "_tile")); effectContainer.addChild(tile2); tile2.startSelfTick(33); tile2.y = (tile2.y - (tile2.height / 2)); var trailsOffsetX:Array = [-1.8, -1.8, 1.8, 1.8, -2.5, -2.5, (1.5 * 2.5), (1.5 * 2.5)]; var trailsOffsetY:Array = [-1, 1, -1, 1, -1, 1, -1, 1]; var t:int; while (t < trailsOffsetX.length) { offsetX = trailsOffsetX[t]; offsetY = trailsOffsetY[t]; trail = GingerFactory.getInstance().instantiate((a_secondaryCharacter.toLowerCase() + "_trail")); effectContainer.addChild(trail); trail.startSelfTick(33); trail.x = ((offsetX * trail.width) / 2); trail.y = ((offsetY * trail.height) / 2); trail.alpha = 0.5; if (t >= 4){ trail.scaleX = 0.5; trail.alpha = 0.2; }; t++; }; var specialGinger:AnimationPlayer = GingerFactory.getInstance().instantiate(("special_" + a_secondaryCharacter.toLowerCase())); effectContainer.addChild(specialGinger); specialGinger.startSelfTick(33); Tweener.addTween(effectContainer, {alpha:1, time:effectTime, onComplete:completeFullScreenAttack, onCompleteParams:[effectContainer, a_player, a_damageType, a_damageAmount]}); } } }//package game
Section 263
//Statistics (game.Statistics) package game { import flash.utils.*; public class Statistics { private var m_stats:Dictionary; public static const TIME_TAKEN:String = "Time Taken"; public static const ENEMIES_KILLED:String = "Enemies Killed"; public static const LARGEST_COMBO:String = "Largest Combo"; public function Statistics(){ m_stats = new Dictionary(); super(); } public function maxStat(a_name:String, a_value:int):void{ var val:int = readStat(a_name); if (a_value > val){ m_stats[a_name] = a_value; }; } public function readStat(a_name:String):int{ if (m_stats[a_name] == null){ return (0); }; return (m_stats[a_name]); } public function increaseStat(a_name:String, a_amount:int):void{ if (m_stats[a_name] == null){ m_stats[a_name] = 0; }; var newValue:int = (int(m_stats[a_name]) + a_amount); m_stats[a_name] = newValue; } } }//package game
Section 264
//TMNTGameDefinition (game.TMNTGameDefinition) package game { import shared.*; import com.urbansquall.prophet.engine.*; import flash.media.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import com.urbansquall.prophet.utils.*; import Box2D.Dynamics.*; import com.urbansquall.prophet.behaviors.*; import game.behaviors.*; public class TMNTGameDefinition extends GameDefinition { public function TMNTGameDefinition(){ var entityDef:EntityTypeDefinition; var circleDef:CircleDef; var polyDef:PolygonDef; var bodyDef:b2BodyDef; var circleGraphicDef:CircleGraphicDefinition; var defaultDensity:Number; var defaultObjectFriction:Number; var defaultRestitution:Number; var horizontalFloatingBehaviorData:KeyValueMap; var groundDetectionData:KeyValueMap; var playerWidth:Number; var objectWidth:Number; var objectHeight:Number; var objectLeftoverHeight:Number; var objectVerticalOffset:Number; var expireData:KeyValueMap; super(); defaultDensity = 5; defaultObjectFriction = 0.65; defaultRestitution = 0; var showDebugBehaviorData:KeyValueMap = new KeyValueMap(); showDebugBehaviorData.setInt("renderLayer", (Constants.ENTITY_DEFAULT_RENDER_LAYER + 1)); showDebugBehaviorData.setBoolean("isDebugEnabled", false); var flinchParams:KeyValueMap; playerWidth = 22; entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_LEONARDO; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); var playerHeight:Number = (38 - CrouchBehavior.CROUCH_HEIGHT); polyDef.makeCenteredBox(((playerWidth / 2) - 2), ((playerHeight / 2) - 0.1), 0, CrouchBehavior.CROUCH_HEIGHT); polyDef.density = PlayerStateMachine.PLAYER_DENSITY; polyDef.friction = 0; polyDef.restitution = 0; polyDef.categoryBits = (polyDef.categoryBits | Constants.PLAYER_COLLISION_CATEGORY); polyDef.maskBits = (polyDef.maskBits | Constants.COMBAT_WAVE_BOUNDARY_COLLISION_CATEGORY); entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.radius = (playerWidth / 2); circleDef.localPosition.y = 25; circleDef.friction = 0.035; circleDef.categoryBits = (circleDef.categoryBits | Constants.PLAYER_COLLISION_CATEGORY); circleDef.maskBits = (circleDef.maskBits | Constants.COMBAT_WAVE_BOUNDARY_COLLISION_CATEGORY); circleDef.restitution = 0; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; groundDetectionData = new KeyValueMap(); groundDetectionData.setNumber("groundSensorWidth", 21); groundDetectionData.setNumber("groundSensorHeight", 16); groundDetectionData.setNumber("groundSensorOffsetY", 32); groundDetectionData.setBoolean("isDebugEnabled", false); entityDef.behaviors.push(new BehaviorDefinition(OnRectangularGroundDetectionBehavior, "ground_detection", groundDetectionData)); entityDef.behaviors.push(new BehaviorDefinition(AirDownAttackBehavior, "shellattack_beh", null)); entityDef.behaviors.push(new BehaviorDefinition(CrouchBehavior, "crouch_beh", null)); var wallDetectionData:KeyValueMap = new KeyValueMap(); wallDetectionData.setNumber("sensorWidth", 6); wallDetectionData.setNumber("sensorHeight", 36); wallDetectionData.setNumber("sensorOffsetX", 12); wallDetectionData.setNumber("sensorOffsetY", 8); entityDef.behaviors.push(new BehaviorDefinition(WallDetectionBehavior, "detect_walls", wallDetectionData)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "leonardo")); entityDef.properties.setBoolean("collectsKeys", true); entityDef.properties.setBoolean("vulnerableToPets", true); entityDef.properties.setBoolean("isTurtle", true); entityDef.properties.setInt("health", 20); entityDef.properties.setInt("ooze", 0); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_MICHELANGELO; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "michelangelo")); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_RAPHAEL; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "raphael")); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_DONATELLO; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "donatello")); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_COMBAT_WAVE; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox(3, 100); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.editorGraphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", polyDef, 0xFF, 0xFF)); entityDef.behaviors.push(new BehaviorDefinition(CombatWaveBehavior, "wave", null)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_NOTE; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox(32, 32); polyDef.density = 2; polyDef.friction = 0.25; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "shell_cell")); entityDef.behaviors.push(new BehaviorDefinition(TriggerTutorialPanelBehavior, "tutorial_behavior", null)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SENTRY; entityDef.fixed = true; circleDef = new CircleDef(); circleDef.radius = 9; circleDef.restitution = defaultRestitution; circleDef.density = 10; circleDef.friction = 0; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); flinchParams.setBoolean("tweenAlphaOnDeath", false); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "sentry")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(SentryBehavior, "sentrybeh", null)); entityDef.properties.setInt("lives", 40); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_ANGRY_SENTRY; entityDef.fixed = true; circleDef = new CircleDef(); circleDef.radius = 9; circleDef.restitution = defaultRestitution; circleDef.density = 10; circleDef.friction = 0; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); flinchParams.setBoolean("tweenAlphaOnDeath", false); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "sentry")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); var sentryKV:KeyValueMap = new KeyValueMap(); sentryKV.setNumber("sensorRange", Constants.RENDER_WIDTH); entityDef.behaviors.push(new BehaviorDefinition(SentryBehavior, "sentrybeh", sentryKV)); entityDef.properties.setInt("lives", 40); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_LINEAR_SENTRY; entityDef.fixed = true; circleDef = new CircleDef(); circleDef.radius = 9; circleDef.restitution = defaultRestitution; circleDef.density = 10; circleDef.friction = 0; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); flinchParams.setBoolean("tweenAlphaOnDeath", false); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "sentry")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); var linearSentryKV:KeyValueMap = new KeyValueMap(); linearSentryKV.setBoolean("isLinear", true); linearSentryKV.setNumber("sensorRange", Constants.RENDER_WIDTH); entityDef.behaviors.push(new BehaviorDefinition(SentryBehavior, "sentrybeh", linearSentryKV)); entityDef.properties.setInt("lives", 40); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_MOUSER; entityDef.fixed = false; circleDef = new CircleDef(); circleDef.localPosition.y = 10; circleDef.radius = 11; circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; var mouserPatrol:KeyValueMap = new KeyValueMap(); mouserPatrol.setInt("entityWidth", ((2 * circleDef.radius) + 8)); mouserPatrol.setInt("entityHeight", (circleDef.radius + 2)); mouserPatrol.setInt("verticalOffset", 0); mouserPatrol.setInt("sensorRadius", 9); flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); flinchParams.setBoolean("tweenAlphaOnDeath", false); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "mouser")); entityDef.behaviors.push(new BehaviorDefinition(PatrolBehavior, "patrolbehavior", mouserPatrol)); entityDef.behaviors.push(new BehaviorDefinition(GraphicsFaceRightBehavior, "grphface", null)); var kotbData:KeyValueMap = new KeyValueMap(); var sound:Sound = new MouserChompNoise1(); kotbData.setString("soundToPlay", "MouserChompNoise1"); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", kotbData)); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 200); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_JUMPING_NINJA; entityDef.fixed = false; polyDef = new PolygonDef(); polyDef.makeCenteredBox((22 / 2), (40 / 2), 0, -8); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.localPosition.y = 24; circleDef.radius = (26 / 2); circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "jumping_ninja")); entityDef.behaviors.push(new BehaviorDefinition(JumpingNinjaBehavior, "jumpingNinjaBehavior", null)); groundDetectionData = new KeyValueMap(); groundDetectionData.setNumber("groundSensorWidth", 19); groundDetectionData.setNumber("groundSensorHeight", 8); groundDetectionData.setNumber("groundSensorOffsetY", 33); groundDetectionData.setBoolean("isDebugEnabled", false); entityDef.behaviors.push(new BehaviorDefinition(OnRectangularGroundDetectionBehavior, "ground_detection", groundDetectionData)); var touchParams:KeyValueMap = new KeyValueMap(); touchParams.setInt("attackDamage", 3); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", touchParams)); flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 365); entityDef.properties.setInt("lives", 365); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SLOTH; entityDef.fixed = false; polyDef = new PolygonDef(); polyDef.makeCenteredBox((50 / 2), (50 / 2), 0, 20); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "sloth")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(SlothBehavior, "slothBehavior", null)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 690); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_JUGGERNAUGHT; entityDef.fixed = false; objectWidth = 30; objectHeight = 88; objectVerticalOffset = 6; objectLeftoverHeight = (objectHeight - objectWidth); polyDef = new PolygonDef(); polyDef.makeCenteredBox(((objectWidth / 2) - 2), (objectLeftoverHeight / 2), 0, ((-(objectWidth) / 2) + objectVerticalOffset)); polyDef.density = defaultDensity; polyDef.friction = 1; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.localPosition.y = ((objectLeftoverHeight / 2) + objectVerticalOffset); circleDef.radius = (objectWidth / 2); circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.linearDamping = 1; bodyDef.allowSleep = false; bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "juggernaught", "walk")); var juggernautStalk:KeyValueMap = new KeyValueMap(); juggernautStalk.setInt("stalkSpeed", 100); entityDef.behaviors.push(new BehaviorDefinition(StalkPlayerBehavior, "stalkPlayer", juggernautStalk)); var juggData:KeyValueMap = new KeyValueMap(); juggData.setInt("attackDamage", 5); juggData.setNumber("attackOffsetX", 20); juggData.setNumber("attackWidth", 54); juggData.setNumber("attackHeight", 36); juggData.setInt("attackSensorWidth", 150); juggData.setInt("STALL_TIME", 40); flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); entityDef.behaviors.push(new BehaviorDefinition(SwordNinjaBehavior, "juggernaut", juggData)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 800); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SWORD_NINJA; entityDef.fixed = false; objectWidth = 20; objectHeight = 68; objectVerticalOffset = 0; objectLeftoverHeight = (objectHeight - objectWidth); polyDef = new PolygonDef(); polyDef.makeCenteredBox(((objectWidth / 2) - 2), (objectLeftoverHeight / 2), 0, ((-(objectWidth) / 2) + objectVerticalOffset)); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.localPosition.y = ((objectLeftoverHeight / 2) + objectVerticalOffset); circleDef.radius = (objectWidth / 2); circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.allowSleep = false; bodyDef.fixedRotation = true; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); var swordNinjaParams:KeyValueMap = new KeyValueMap(); entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "sword_ninja", "walk")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(StalkPlayerBehavior, "stalkPlayer", null)); entityDef.behaviors.push(new BehaviorDefinition(SwordNinjaBehavior, "swordNinja", swordNinjaParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 365); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SWORD_NINJA_PASSIVE; entityDef.fixed = false; polyDef = new PolygonDef(); polyDef.makeCenteredBox((20 / 2), (68 / 2), 0, 6); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.allowSleep = false; bodyDef.fixedRotation = true; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "sword_ninja", "walk")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(SwordNinjaBehavior, "swordNinja", null)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 365); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_BLOWGUN_NINJA; entityDef.fixed = false; polyDef = new PolygonDef(); polyDef.makeCenteredBox((68 / 2), (24 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "blowgun_ninja")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); var data:KeyValueMap = new KeyValueMap(); data.setNumber("offsetX", 45); data.setNumber("offsetY", 0); data.setString("projectileType", Constants.ENTITY_TYPE_DART); entityDef.behaviors.push(new BehaviorDefinition(ShurikenNinjaBehavior, "throw_shuriks", data)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 40); entityDef.properties.setBoolean("canBeStoodOn", false); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SHURIKEN_NINJA; entityDef.fixed = false; polyDef = new PolygonDef(); polyDef.makeCenteredBox((20 / 2), (58 / 2), 0, 8); polyDef.density = defaultDensity; polyDef.friction = 1; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; bodyDef.linearDamping = 1; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "shuriken_ninja")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(ShurikenNinjaBehavior, "throw_shuriks", null)); entityDef.behaviors.push(new BehaviorDefinition(WeaknessToAcidBehavior, "acidicweak", null)); entityDef.properties.setInt("lives", 185); entityDef.properties.setBoolean("canBeStoodOn", false); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); this.registerEntityType(entityDef); var specialProjectileAttackLivingTime = 925; var projectileHeight:Number = 86; entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SPECIAL_RAPHAEL; entityDef.fixed = false; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.makeCenteredBox((80 / 2), (projectileHeight / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new StaticGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "trail", AssetLibrary.RAPHAEL_TRAIL, ((-9 * 128) * 0.5), 0, true, 9, 1)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "image", "special_raphael")); entityDef.behaviors.push(new BehaviorDefinition(AntiGravityBehavior, "antigravity", null)); entityDef.behaviors.push(new BehaviorDefinition(MovingSpecialAttackBehavior, "specattack", null)); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("ignoresBoundaries", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SPECIAL_PIZZA_DELIVERY; entityDef.fixed = false; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.makeCenteredBox((150 / 2), (projectileHeight / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "special_pizza_dude")); entityDef.behaviors.push(new BehaviorDefinition(PizzaDudeBehavior, "pizzadude", null)); entityDef.behaviors.push(new BehaviorDefinition(AntiGravityBehavior, "antigravity", null)); expireData = new KeyValueMap(); expireData.setNumber("livingTime", 1200); entityDef.behaviors.push(new BehaviorDefinition(ExpireBehavior, "expire", expireData)); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("ignoresBoundaries", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SPECIAL_MICHELANGELO; entityDef.fixed = false; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.makeCenteredBox((80 / 2), (projectileHeight / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new StaticGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "trail", AssetLibrary.MICHELANGEO_TRAIL, ((-9 * 128) * 0.5), 0, true, 9, 1)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "image", "special_michelangelo")); entityDef.behaviors.push(new BehaviorDefinition(AntiGravityBehavior, "antigravity", null)); var attackData:KeyValueMap = new KeyValueMap(); attackData.setString("damageType", "robots"); attackData.setInt("damageAmount", 400); entityDef.behaviors.push(new BehaviorDefinition(MovingSpecialAttackBehavior, "specattack", attackData)); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("ignoresBoundaries", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SPECIAL_CASEY_JONES; entityDef.fixed = false; entityDef.pruneType = PruneType.IMMUNE; polyDef = new PolygonDef(); polyDef.makeCenteredBox((150 / 2), (projectileHeight / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new StaticGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "trail", AssetLibrary.CASEY_JONES_TRAIL, ((-9 * 128) * 0.5), 0, true, 9, 1)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 2), "image", "special_casey_jones")); entityDef.behaviors.push(new BehaviorDefinition(AntiGravityBehavior, "antigravity", null)); attackData = new KeyValueMap(); attackData.setString("damageType", "none"); attackData.setInt("damageAmount", 850); entityDef.behaviors.push(new BehaviorDefinition(MovingSpecialAttackBehavior, "specattack", attackData)); entityDef.properties.setBoolean("isHuman", false); entityDef.properties.setBoolean("ignoresBoundaries", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SHURIKEN; entityDef.fixed = false; entityDef.pruneType = PruneType.DIE; polyDef = new PolygonDef(); polyDef.makeCenteredBox((10 / 2), (3 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "shuriken")); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(DieOnTouchSomethingBehavior, "die_on_touch", null)); entityDef.behaviors.push(new BehaviorDefinition(AntiGravityBehavior, "antigravity", null)); expireData = new KeyValueMap(); expireData.setNumber("livingTime", 1290); entityDef.behaviors.push(new BehaviorDefinition(ExpireBehavior, "expire", expireData)); entityDef.properties.setInt("lives", 1); entityDef.properties.setBoolean("isHuman", false); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_DART; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "dart")); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_LASER_NINJA; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((25 / 2), (64 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.allowSleep = false; bodyDef.fixedRotation = true; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "laser_ninja")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(LaserNinjaBehavior, "laserninja", null)); entityDef.behaviors.push(new BehaviorDefinition(GraphicsFaceRightBehavior, "grphface", null)); entityDef.properties.setInt("lives", 605); entityDef.properties.setBoolean("canBeStoodOn", false); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_LASER; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((4 / 2), (360 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 1), "image", "laser")); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(LaserBehavior, "laser", null)); entityDef.properties.setInt("lives", 1000); entityDef.properties.setBoolean("isHuman", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SHREDDER; entityDef.fixed = false; objectWidth = 36; objectHeight = 60; objectVerticalOffset = 16; objectLeftoverHeight = (objectHeight - objectWidth); polyDef = new PolygonDef(); polyDef.makeCenteredBox(((objectWidth / 2) - 2), (objectLeftoverHeight / 2), 0, ((-(objectWidth) / 2) + objectVerticalOffset)); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.localPosition.y = ((objectLeftoverHeight / 2) + objectVerticalOffset); circleDef.radius = (objectWidth / 2); circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "shredder")); flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(ShredderBehavior, "shredderBehavior", null)); var shredderWallDetect:KeyValueMap = new KeyValueMap(); shredderWallDetect.setBoolean("requireGrabbableWalls", false); shredderWallDetect.setNumber("sensorWidth", 6); shredderWallDetect.setNumber("sensorHeight", 36); shredderWallDetect.setNumber("sensorOffsetX", 18); shredderWallDetect.setNumber("sensorOffsetY", 8); shredderWallDetect.setBoolean("drawShapes", false); entityDef.behaviors.push(new BehaviorDefinition(WallDetectionBehavior, "walldetect", shredderWallDetect)); groundDetectionData = new KeyValueMap(); groundDetectionData.setNumber("groundSensorWidth", 12); groundDetectionData.setNumber("groundSensorHeight", 8); groundDetectionData.setNumber("groundSensorOffsetY", 48); groundDetectionData.setNumber("groundSensorOffsetX", 0); groundDetectionData.setBoolean("isDebugEnabled", false); entityDef.behaviors.push(new BehaviorDefinition(OnRectangularGroundDetectionBehavior, "ground_detection", groundDetectionData)); entityDef.properties.setInt("lives", 3000); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_CLONE_SHREDDER; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "super_shredder")); var cloneShredderDef:KeyValueMap = new KeyValueMap(); cloneShredderDef.setInt("JUMP_HEIGHT", 480); cloneShredderDef.setInt("LEFT_EDGE", 660); cloneShredderDef.setInt("RIGHT_EDGE", 1150); cloneShredderDef.setInt("JUMP_ATTEMPTS", 2); cloneShredderDef.setBoolean("IS_CLONE", true); entityDef.behaviors.splice(2, 1, new BehaviorDefinition(ShredderBehavior, "shredderBehavior", cloneShredderDef)); entityDef.properties.setInt("lives", 450); this.registerEntityType(entityDef); entityDef = entityDef.clone(); entityDef.type = Constants.ENTITY_TYPE_SUPER_SHREDDER; entityDef.graphics.splice(0); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 1), "image", "super_shredder")); var superShredderDef:KeyValueMap = new KeyValueMap(); superShredderDef.setInt("MOVE_SPEED", 130); superShredderDef.setInt("DASH_DISTANCE", 165); superShredderDef.setInt("DASH_SPEED", 260); superShredderDef.setInt("ATTACK_DELAY", 20); superShredderDef.setInt("JUMP_SPEED", 440); superShredderDef.setInt("KICK_SPEED", 580); superShredderDef.setInt("JUMP_ATTEMPTS", 5); superShredderDef.setInt("HENCHMEN_COUNT", 1); superShredderDef.setString("HENCHMAN", Constants.ENTITY_TYPE_CLONE_SHREDDER); superShredderDef.setInt("PUNCH_DISTANCE", 65); superShredderDef.setInt("PUNCH_DAMAGE", 5); superShredderDef.setInt("JUMP_HEIGHT", 480); superShredderDef.setInt("LEFT_EDGE", 660); superShredderDef.setInt("RIGHT_EDGE", 1150); entityDef.behaviors.splice(2, 1, new BehaviorDefinition(ShredderBehavior, "shredderBehavior", superShredderDef)); entityDef.properties.setInt("lives", 4000); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_ELECTRICAL_WALL; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((48 / 2), (96 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "electrical_wall")); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.properties.setInt("lives", 25); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_BREAKABLE_WALL; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((48 / 2), (96 / 2), 0, 0); polyDef.density = 10000; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "breakable_wall")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", null)); entityDef.behaviors.push(new BehaviorDefinition(BreakableWallBehavior, "breaks", null)); entityDef.properties.setInt("lives", 900); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_HUN; entityDef.fixed = false; objectWidth = 48; objectHeight = 100; objectVerticalOffset = 20; objectLeftoverHeight = (objectHeight - objectWidth); polyDef = new PolygonDef(); polyDef.makeCenteredBox(((objectWidth / 2) - 2), (objectLeftoverHeight / 2), 0, ((-(objectWidth) / 2) + objectVerticalOffset)); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; polyDef.restitution = defaultRestitution; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(polyDef); circleDef = new CircleDef(); circleDef.localPosition.y = ((objectLeftoverHeight / 2) + objectVerticalOffset); circleDef.radius = (objectWidth / 2); circleDef.density = defaultDensity; circleDef.friction = defaultObjectFriction; circleDef.restitution = defaultRestitution; circleDef.groupFilter = Constants.ENEMY_GROUP_FILTER; entityDef.shapes.push(circleDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; bodyDef.allowSleep = false; entityDef.physics = bodyDef; flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "human"); flinchParams.setBoolean("tweenAlphaOnDeath", false); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "hun")); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); entityDef.behaviors.push(new BehaviorDefinition(HunBehavior, "hun", null)); var hunWallDetect:KeyValueMap = new KeyValueMap(); hunWallDetect.setBoolean("requireGrabbableWalls", false); hunWallDetect.setNumber("sensorWidth", 6); hunWallDetect.setNumber("sensorHeight", 36); hunWallDetect.setNumber("sensorOffsetX", 32); hunWallDetect.setNumber("sensorOffsetY", 8); hunWallDetect.setBoolean("drawShapes", false); entityDef.behaviors.push(new BehaviorDefinition(WallDetectionBehavior, "walldetect", hunWallDetect)); hunWallDetect = null; entityDef.properties.setInt("lives", 2400); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", true); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_PIZZA; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((24 / 2), (26 / 2), 0, 0); polyDef.density = 0; polyDef.friction = 0; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; var healData:KeyValueMap = new KeyValueMap(); healData.setInt("healAmount", 2); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "pizza_slice")); expireData = new KeyValueMap(); expireData.setBoolean("expireEnabled", false); expireData.setNumber("livingTime", 2500); expireData.setBoolean("tweenOut", true); entityDef.behaviors.push(new BehaviorDefinition(ExpireBehavior, "expire", expireData)); entityDef.behaviors.push(new BehaviorDefinition(HealthItemBehavior, "healplayer", healData)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_FULL_PIZZA; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((32 / 2), (32 / 2), 0, 0); polyDef.density = 0; polyDef.friction = 0; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "full_pizza")); var fullPizzaHealData:KeyValueMap = new KeyValueMap(); fullPizzaHealData.setInt("healAmount", 10); entityDef.behaviors.push(new BehaviorDefinition(HealthItemBehavior, "healplayer", fullPizzaHealData)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_OOZE_CANNISTER; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((28 / 2), (36 / 2), 0, 0); polyDef.density = 0; polyDef.friction = 0; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "ooze_cannister")); var chargeData:KeyValueMap = new KeyValueMap(); chargeData.setInt("chargeAmount", 10); entityDef.behaviors.push(new BehaviorDefinition(ChargeSpecialItemBehavior, "chargeplayerspecial", chargeData)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_OOZE_CAN; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((16 / 2), (18 / 2), 0, 0); polyDef.density = 0; polyDef.friction = 0; polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "ooze_drop")); chargeData = new KeyValueMap(); chargeData.setInt("chargeAmount", 1); entityDef.behaviors.push(new BehaviorDefinition(ChargeSpecialItemBehavior, "chargeplayerspecial", chargeData)); expireData = new KeyValueMap(); expireData.setBoolean("expireEnabled", false); expireData.setNumber("livingTime", 2500); expireData.setBoolean("tweenOut", true); entityDef.behaviors.push(new BehaviorDefinition(ExpireBehavior, "expire", expireData)); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SWITCH; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.isSensor = true; polyDef.makeCenteredBox((30 / 2), (21 / 2), 0, 0); polyDef.density = defaultDensity; polyDef.friction = defaultObjectFriction; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); bodyDef.fixedRotation = true; entityDef.physics = bodyDef; entityDef.behaviors.push(new BehaviorDefinition(SwitchBehavior, "switchbehaviour", null)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 2), "image", "switch")); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_DRILL_BOX; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.isSensor = false; polyDef.groupFilter = Constants.ENEMY_GROUP_FILTER; polyDef.density = 2.5; var vertexOffsetX:Number = -46; var vertexOffsetY:Number = -64; polyDef.addVertex((vertexOffsetX + 27), (vertexOffsetY + 32)); polyDef.addVertex((vertexOffsetX + 47), (vertexOffsetY + 7)); polyDef.addVertex((vertexOffsetX + 66), (vertexOffsetY + 29)); polyDef.addVertex((vertexOffsetX + 67), (vertexOffsetY + 122)); polyDef.addVertex((vertexOffsetX + 27), (vertexOffsetY + 121)); entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 2), "image", "drill_box")); entityDef.editorGraphics.push(new PolygonGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "drillShape", polyDef, 0xFF0000, 0xFF0000)); entityDef.behaviors.push(new BehaviorDefinition(DrillBoxBehavior, "drillbox", null)); entityDef.behaviors.push(new BehaviorDefinition(KnockbackOnTouchBehavior, "bounceplayer", null)); flinchParams = new KeyValueMap(); flinchParams.setString("soundProfile", "robot"); entityDef.behaviors.push(new BehaviorDefinition(FlinchBehavior, "flinch", flinchParams)); entityDef.properties.setInt("lives", 900); entityDef.properties.setBoolean("isEnemy", true); entityDef.properties.setBoolean("isHuman", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_CRUMBLING_BLOCK; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.makeCenteredBox((64 / 2), (32 / 2), 0, 10); polyDef.isSensor = true; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.properties.setBoolean("safeToRespawnTo", false); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "crumbling_block")); entityDef.behaviors.push(new BehaviorDefinition(CrumblingBlockBehavior, "crumblingBlock", null)); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_PLATFORM; entityDef.fixed = true; entityDef.pruneType = PruneType.RESPAWN; polyDef = new PolygonDef(); polyDef.makeCenteredBox((64 / 2), (16 / 2), 0, -8); polyDef.density = 50000; polyDef.friction = 1; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.properties.setBoolean("safeToRespawnTo", false); entityDef.graphics.push(new GingerGraphicDefinition(Constants.ENTITY_DEFAULT_RENDER_LAYER, "image", "platform")); entityDef.behaviors.push(new BehaviorDefinition(RailPlatformBehavior, "railplatform", null)); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_SPECIAL_SPLINTER; entityDef.fixed = true; bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.behaviors.push(new BehaviorDefinition(SplinterSpecialAttackBehavior, "specialAttack", null)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER + 10), "image", "special_splinter")); entityDef.properties.setBoolean("canBeStoodOn", false); this.registerEntityType(entityDef); entityDef = new EntityTypeDefinition(); entityDef.type = Constants.ENTITY_TYPE_EXIT; entityDef.fixed = true; polyDef = new PolygonDef(); polyDef.isSensor = true; polyDef.makeCenteredBox((36 / 2), (150 / 2)); polyDef.density = 2.5; entityDef.shapes.push(polyDef); bodyDef = new b2BodyDef(); entityDef.physics = bodyDef; entityDef.graphics.push(new StaticGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 10), "back", AssetLibrary.EXIT_BOTTOM, 0, -60)); entityDef.graphics.push(new GingerGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 9), "image", "exit")); entityDef.graphics.push(new StaticGraphicDefinition((Constants.ENTITY_DEFAULT_RENDER_LAYER - 8), "front", AssetLibrary.EXIT_OVERLAY, 0, -60)); entityDef.behaviors.push(new BehaviorDefinition(OnTouchExitBehavior, "touchExit", null)); this.registerEntityType(entityDef); } } }//package game
Section 265
//BitmapAsset (mx.core.BitmapAsset) package mx.core { import flash.display.*; public class BitmapAsset extends FlexBitmap implements IFlexAsset, IFlexDisplayObject { mx_internal static const VERSION:String = "3.3.0.4852"; public function BitmapAsset(bitmapData:BitmapData=null, pixelSnapping:String="auto", smoothing:Boolean=false){ super(bitmapData, pixelSnapping, smoothing); } public function get measuredWidth():Number{ if (bitmapData){ return (bitmapData.width); }; return (0); } public function get measuredHeight():Number{ if (bitmapData){ return (bitmapData.height); }; return (0); } public function setActualSize(newWidth:Number, newHeight:Number):void{ width = newWidth; height = newHeight; } public function move(x:Number, y:Number):void{ this.x = x; this.y = y; } } }//package mx.core
Section 266
//ByteArrayAsset (mx.core.ByteArrayAsset) package mx.core { import flash.utils.*; public class ByteArrayAsset extends ByteArray implements IFlexAsset { mx_internal static const VERSION:String = "3.3.0.4852"; public function ByteArrayAsset(){ super(); } } }//package mx.core
Section 267
//FlexBitmap (mx.core.FlexBitmap) package mx.core { import flash.display.*; import mx.utils.*; public class FlexBitmap extends Bitmap { mx_internal static const VERSION:String = "3.3.0.4852"; public function FlexBitmap(bitmapData:BitmapData=null, pixelSnapping:String="auto", smoothing:Boolean=false){ var bitmapData = bitmapData; var pixelSnapping = pixelSnapping; var smoothing = smoothing; super(bitmapData, pixelSnapping, smoothing); name = NameUtil.createUniqueName(this); //unresolved jump var _slot1 = e; } override public function toString():String{ return (NameUtil.displayObjectToString(this)); } } }//package mx.core
Section 268
//FontAsset (mx.core.FontAsset) package mx.core { import flash.text.*; public class FontAsset extends Font implements IFlexAsset { mx_internal static const VERSION:String = "3.3.0.4852"; public function FontAsset(){ super(); } } }//package mx.core
Section 269
//IFlexAsset (mx.core.IFlexAsset) package mx.core { public interface IFlexAsset { } }//package mx.core
Section 270
//IFlexDisplayObject (mx.core.IFlexDisplayObject) package mx.core { import flash.events.*; import flash.display.*; import flash.geom.*; import flash.accessibility.*; public interface IFlexDisplayObject extends IBitmapDrawable, IEventDispatcher { function get visible():Boolean; function get rotation():Number; function localToGlobal(void:Point):Point; function get name():String; function set width(flash.display:Number):void; function get measuredHeight():Number; function get blendMode():String; function get scale9Grid():Rectangle; function set name(flash.display:String):void; function set scaleX(flash.display:Number):void; function set scaleY(flash.display:Number):void; function get measuredWidth():Number; function get accessibilityProperties():AccessibilityProperties; function set scrollRect(flash.display:Rectangle):void; function get cacheAsBitmap():Boolean; function globalToLocal(void:Point):Point; function get height():Number; function set blendMode(flash.display:String):void; function get parent():DisplayObjectContainer; function getBounds(String:DisplayObject):Rectangle; function get opaqueBackground():Object; function set scale9Grid(flash.display:Rectangle):void; function setActualSize(_arg1:Number, _arg2:Number):void; function set alpha(flash.display:Number):void; function set accessibilityProperties(flash.display:AccessibilityProperties):void; function get width():Number; function hitTestPoint(_arg1:Number, _arg2:Number, _arg3:Boolean=false):Boolean; function set cacheAsBitmap(flash.display:Boolean):void; function get scaleX():Number; function get scaleY():Number; function get scrollRect():Rectangle; function get mouseX():Number; function get mouseY():Number; function set height(flash.display:Number):void; function set mask(flash.display:DisplayObject):void; function getRect(String:DisplayObject):Rectangle; function get alpha():Number; function set transform(flash.display:Transform):void; function move(_arg1:Number, _arg2:Number):void; function get loaderInfo():LoaderInfo; function get root():DisplayObject; function hitTestObject(mx.core:IFlexDisplayObject/mx.core:IFlexDisplayObject:stage/get:DisplayObject):Boolean; function set opaqueBackground(flash.display:Object):void; function set visible(flash.display:Boolean):void; function get mask():DisplayObject; function set x(flash.display:Number):void; function set y(flash.display:Number):void; function get transform():Transform; function set filters(flash.display:Array):void; function get x():Number; function get y():Number; function get filters():Array; function set rotation(flash.display:Number):void; function get stage():Stage; } }//package mx.core
Section 271
//IRepeaterClient (mx.core.IRepeaterClient) package mx.core { public interface IRepeaterClient { function get instanceIndices():Array; function set instanceIndices(C:\autobuild\3.3.0\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function get isDocument():Boolean; function set repeaters(C:\autobuild\3.3.0\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function initializeRepeaterArrays(C:\autobuild\3.3.0\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:IRepeaterClient):void; function get repeaters():Array; function set repeaterIndices(C:\autobuild\3.3.0\frameworks\projects\framework\src;mx\core;IRepeaterClient.as:Array):void; function get repeaterIndices():Array; } }//package mx.core
Section 272
//mx_internal (mx.core.mx_internal) package mx.core { public namespace mx_internal = "http://www.adobe.com/2006/flex/mx/internal"; }//package mx.core
Section 273
//NameUtil (mx.utils.NameUtil) package mx.utils { import flash.display.*; import flash.utils.*; import mx.core.*; public class NameUtil { mx_internal static const VERSION:String = "3.3.0.4852"; private static var counter:int = 0; public function NameUtil(){ super(); } public static function displayObjectToString(displayObject:DisplayObject):String{ var result:String; var o:DisplayObject; var s:String; var indices:Array; var displayObject = displayObject; o = displayObject; while (o != null) { if (((((o.parent) && (o.stage))) && ((o.parent == o.stage)))){ break; }; s = o.name; if ((o is IRepeaterClient)){ indices = IRepeaterClient(o).instanceIndices; if (indices){ s = (s + (("[" + indices.join("][")) + "]")); }; }; result = ((result == null)) ? s : ((s + ".") + result); o = o.parent; }; //unresolved jump var _slot1 = e; return (result); } public static function createUniqueName(object:Object):String{ if (!object){ return (null); }; var name:String = getQualifiedClassName(object); var index:int = name.indexOf("::"); if (index != -1){ name = name.substr((index + 2)); }; var charCode:int = name.charCodeAt((name.length - 1)); if ((((charCode >= 48)) && ((charCode <= 57)))){ name = (name + "_"); }; return ((name + counter++)); } } }//package mx.utils
Section 274
//AssetLibrary (shared.AssetLibrary) package shared { public class AssetLibrary { public static const DONATELLO:Class = AssetLibrary_DONATELLO; public static const RAPHAEL_TRAIL:Class = AssetLibrary_RAPHAEL_TRAIL; public static const SLOTH:Class = AssetLibrary_SLOTH; public static const ROOF_WALL_SLICK:Class = AssetLibrary_ROOF_WALL_SLICK; public static const EXIT_OVERLAY:Class = AssetLibrary_EXIT_OVERLAY; public static const SPECIAL_DONATELLO:Class = AssetLibrary_SPECIAL_DONATELLO; private static const s_forceCompile:Array = [MUSIC_BOSS, MUSIC_UI]; public static const MUTE_BUTTON:Class = AssetLibrary_MUTE_BUTTON; public static const BLOWGUN_NINJA:Class = AssetLibrary_BLOWGUN_NINJA; public static const PORTRAIT_MICHELANGELO:Class = AssetLibrary_PORTRAIT_MICHELANGELO; public static const JUMP_DUST:Class = AssetLibrary_JUMP_DUST; public static const LEVEL_LOCK:Class = AssetLibrary_LEVEL_LOCK; public static const KANJI_NINJA:Class = AssetLibrary_KANJI_NINJA; public static const BTN_OVERLAY:Class = AssetLibrary_BTN_OVERLAY; public static const SHELL_CELL:Class = AssetLibrary_SHELL_CELL; public static const SWITCH:Class = AssetLibrary_SWITCH; public static const WAREHOUSE_TILESET:Class = AssetLibrary_WAREHOUSE_TILESET; public static const PORTRAIT_RAPHAEL:Class = AssetLibrary_PORTRAIT_RAPHAEL; public static const JUMPING_NINJA:Class = AssetLibrary_JUMPING_NINJA; public static const STREETS_TILESET:Class = AssetLibrary_STREETS_TILESET; public static const SPECIAL_RAPHAEL:Class = AssetLibrary_SPECIAL_RAPHAEL; public static const HIT_EFFECT_1:Class = AssetLibrary_HIT_EFFECT_1; public static const HIT_EFFECT_3:Class = AssetLibrary_HIT_EFFECT_3; public static const PACKSHOT_SMALL:Class = AssetLibrary_PACKSHOT_SMALL; public static const SIGN_BUBBLE:Class = AssetLibrary_SIGN_BUBBLE; public static const HIT_EFFECT_2:Class = AssetLibrary_HIT_EFFECT_2; public static const SPECIAL_PIZZA_DELIVERY:Class = AssetLibrary_SPECIAL_PIZZA_DELIVERY; public static const ROOF_WALL:Class = AssetLibrary_ROOF_WALL; public static const TITLE_LOGO:Class = AssetLibrary_TITLE_LOGO; public static const PORTRAIT_DONATELLO:Class = AssetLibrary_PORTRAIT_DONATELLO; public static const ROOF_TILESET:Class = AssetLibrary_ROOF_TILESET; public static const MICHELANGEO_TRAIL:Class = AssetLibrary_MICHELANGEO_TRAIL; public static const EXIT_BOTTOM:Class = AssetLibrary_EXIT_BOTTOM; public static const MOUSER:Class = AssetLibrary_MOUSER; public static const PIZZA:Class = AssetLibrary_PIZZA; public static const PLATFORM:Class = AssetLibrary_PLATFORM; public static const PORTRAIT_PIZZA_DUDE:Class = AssetLibrary_PORTRAIT_PIZZA_DUDE; public static const SHREDDER:Class = AssetLibrary_SHREDDER; public static const LEONARDO_TILE:Class = AssetLibrary_LEONARDO_TILE; public static const STREET_STATIC_BG:Class = AssetLibrary_STREET_STATIC_BG; public static const OOZE_CAN:Class = AssetLibrary_OOZE_CAN; public static const EXIT_TURTLE:Class = AssetLibrary_EXIT_TURTLE; public static const LEVEL_MARKERS:Class = AssetLibrary_LEVEL_MARKERS; public static const DART:Class = AssetLibrary_DART; public static const LEONARDO_TRAIL:Class = AssetLibrary_LEONARDO_TRAIL; public static const OOZE_CANNISTER:Class = AssetLibrary_OOZE_CANNISTER; public static const PACKSHOT_LARGE:Class = AssetLibrary_PACKSHOT_LARGE; public static const BTN_TILE9:Class = AssetLibrary_BTN_TILE9; public static const SPECIAL_SPLINTER:Class = AssetLibrary_SPECIAL_SPLINTER; public static const BREAKABLE_WALL:Class = AssetLibrary_BREAKABLE_WALL; public static const ROOF_TOP_EDGE:Class = AssetLibrary_ROOF_TOP_EDGE; public static const CAMPAIGN_SCREEN:Class = AssetLibrary_CAMPAIGN_SCREEN; public static const LEONARDO:Class = AssetLibrary_LEONARDO; public static const KANJI_ATTACK:Class = AssetLibrary_KANJI_ATTACK; public static const LEVEL_CHECKMARK:Class = AssetLibrary_LEVEL_CHECKMARK; public static const ELECTRICAL_WALL:Class = AssetLibrary_ELECTRICAL_WALL; public static const PUT_THIS_GAME:Class = AssetLibrary_PUT_THIS_GAME; public static const DONATELLO_TILE:Class = AssetLibrary_DONATELLO_TILE; public static const DRILL_BOX:Class = AssetLibrary_DRILL_BOX; public static const SHURIKEN_NINJA:Class = AssetLibrary_SHURIKEN_NINJA; public static const JUGGERNAUGHT:Class = AssetLibrary_JUGGERNAUGHT; public static const LASER:Class = AssetLibrary_LASER; public static const CASEY_JONES_TRAIL:Class = AssetLibrary_CASEY_JONES_TRAIL; public static const PORTRAIT_SPLINTER:Class = AssetLibrary_PORTRAIT_SPLINTER; public static const SPECIAL_LEONARDO:Class = AssetLibrary_SPECIAL_LEONARDO; public static const URBANSQUALL_BUTTON:Class = AssetLibrary_URBANSQUALL_BUTTON; public static const INPUT_HELP:Class = AssetLibrary_INPUT_HELP; public static const FULL_PIZZA:Class = AssetLibrary_FULL_PIZZA; public static const KANJI_RAT:Class = AssetLibrary_KANJI_RAT; public static const PORTRAIT_LEONARDO:Class = AssetLibrary_PORTRAIT_LEONARDO; public static const UBISOFT_LOGO:Class = AssetLibrary_UBISOFT_LOGO; public static const SUPER_SHREDDER:Class = AssetLibrary_SUPER_SHREDDER; public static const SPECIAL_CASEY_JONES:Class = AssetLibrary_SPECIAL_CASEY_JONES; public static const SPECIAL_MICHELANGELO:Class = AssetLibrary_SPECIAL_MICHELANGELO; public static const LASER_NINJA:Class = AssetLibrary_LASER_NINJA; public static const SENTRY:Class = AssetLibrary_SENTRY; public static const RAPHAEL:Class = AssetLibrary_RAPHAEL; public static const PANEL:Class = AssetLibrary_PANEL; public static const ROOFTOP_STATIC_BG:Class = AssetLibrary_ROOFTOP_STATIC_BG; public static const HUN:Class = AssetLibrary_HUN; public static const FS_SWORD:Class = AssetLibrary_FS_SWORD; public static const DONATELLO_TRAIL:Class = AssetLibrary_DONATELLO_TRAIL; public static const PORTRAIT_CASEY_JONES:Class = AssetLibrary_PORTRAIT_CASEY_JONES; public static const MICHELANGELO:Class = AssetLibrary_MICHELANGELO; public static const SHURIKEN:Class = AssetLibrary_SHURIKEN; public static const CRUMBLING_BLOCK:Class = AssetLibrary_CRUMBLING_BLOCK; public function AssetLibrary(){ super(); } } }//package shared
Section 275
//AssetLibrary_BLOWGUN_NINJA (shared.AssetLibrary_BLOWGUN_NINJA) package shared { import mx.core.*; public class AssetLibrary_BLOWGUN_NINJA extends BitmapAsset { } }//package shared
Section 276
//AssetLibrary_BREAKABLE_WALL (shared.AssetLibrary_BREAKABLE_WALL) package shared { import mx.core.*; public class AssetLibrary_BREAKABLE_WALL extends BitmapAsset { } }//package shared
Section 277
//AssetLibrary_BTN_OVERLAY (shared.AssetLibrary_BTN_OVERLAY) package shared { import mx.core.*; public class AssetLibrary_BTN_OVERLAY extends BitmapAsset { } }//package shared
Section 278
//AssetLibrary_BTN_TILE9 (shared.AssetLibrary_BTN_TILE9) package shared { import mx.core.*; public class AssetLibrary_BTN_TILE9 extends BitmapAsset { } }//package shared
Section 279
//AssetLibrary_CAMPAIGN_SCREEN (shared.AssetLibrary_CAMPAIGN_SCREEN) package shared { import mx.core.*; public class AssetLibrary_CAMPAIGN_SCREEN extends BitmapAsset { } }//package shared
Section 280
//AssetLibrary_CASEY_JONES_TRAIL (shared.AssetLibrary_CASEY_JONES_TRAIL) package shared { import mx.core.*; public class AssetLibrary_CASEY_JONES_TRAIL extends BitmapAsset { } }//package shared
Section 281
//AssetLibrary_CRUMBLING_BLOCK (shared.AssetLibrary_CRUMBLING_BLOCK) package shared { import mx.core.*; public class AssetLibrary_CRUMBLING_BLOCK extends BitmapAsset { } }//package shared
Section 282
//AssetLibrary_DART (shared.AssetLibrary_DART) package shared { import mx.core.*; public class AssetLibrary_DART extends BitmapAsset { } }//package shared
Section 283
//AssetLibrary_DONATELLO (shared.AssetLibrary_DONATELLO) package shared { import mx.core.*; public class AssetLibrary_DONATELLO extends BitmapAsset { } }//package shared
Section 284
//AssetLibrary_DONATELLO_TILE (shared.AssetLibrary_DONATELLO_TILE) package shared { import mx.core.*; public class AssetLibrary_DONATELLO_TILE extends BitmapAsset { } }//package shared
Section 285
//AssetLibrary_DONATELLO_TRAIL (shared.AssetLibrary_DONATELLO_TRAIL) package shared { import mx.core.*; public class AssetLibrary_DONATELLO_TRAIL extends BitmapAsset { } }//package shared
Section 286
//AssetLibrary_DRILL_BOX (shared.AssetLibrary_DRILL_BOX) package shared { import mx.core.*; public class AssetLibrary_DRILL_BOX extends BitmapAsset { } }//package shared
Section 287
//AssetLibrary_ELECTRICAL_WALL (shared.AssetLibrary_ELECTRICAL_WALL) package shared { import mx.core.*; public class AssetLibrary_ELECTRICAL_WALL extends BitmapAsset { } }//package shared
Section 288
//AssetLibrary_EXIT_BOTTOM (shared.AssetLibrary_EXIT_BOTTOM) package shared { import mx.core.*; public class AssetLibrary_EXIT_BOTTOM extends BitmapAsset { } }//package shared
Section 289
//AssetLibrary_EXIT_OVERLAY (shared.AssetLibrary_EXIT_OVERLAY) package shared { import mx.core.*; public class AssetLibrary_EXIT_OVERLAY extends BitmapAsset { } }//package shared
Section 290
//AssetLibrary_EXIT_TURTLE (shared.AssetLibrary_EXIT_TURTLE) package shared { import mx.core.*; public class AssetLibrary_EXIT_TURTLE extends BitmapAsset { } }//package shared
Section 291
//AssetLibrary_FS_SWORD (shared.AssetLibrary_FS_SWORD) package shared { import mx.core.*; public class AssetLibrary_FS_SWORD extends BitmapAsset { } }//package shared
Section 292
//AssetLibrary_FULL_PIZZA (shared.AssetLibrary_FULL_PIZZA) package shared { import mx.core.*; public class AssetLibrary_FULL_PIZZA extends BitmapAsset { } }//package shared
Section 293
//AssetLibrary_HIT_EFFECT_1 (shared.AssetLibrary_HIT_EFFECT_1) package shared { import mx.core.*; public class AssetLibrary_HIT_EFFECT_1 extends BitmapAsset { } }//package shared
Section 294
//AssetLibrary_HIT_EFFECT_2 (shared.AssetLibrary_HIT_EFFECT_2) package shared { import mx.core.*; public class AssetLibrary_HIT_EFFECT_2 extends BitmapAsset { } }//package shared
Section 295
//AssetLibrary_HIT_EFFECT_3 (shared.AssetLibrary_HIT_EFFECT_3) package shared { import mx.core.*; public class AssetLibrary_HIT_EFFECT_3 extends BitmapAsset { } }//package shared
Section 296
//AssetLibrary_HUN (shared.AssetLibrary_HUN) package shared { import mx.core.*; public class AssetLibrary_HUN extends BitmapAsset { } }//package shared
Section 297
//AssetLibrary_INPUT_HELP (shared.AssetLibrary_INPUT_HELP) package shared { import mx.core.*; public class AssetLibrary_INPUT_HELP extends BitmapAsset { } }//package shared
Section 298
//AssetLibrary_JUGGERNAUGHT (shared.AssetLibrary_JUGGERNAUGHT) package shared { import mx.core.*; public class AssetLibrary_JUGGERNAUGHT extends BitmapAsset { } }//package shared
Section 299
//AssetLibrary_JUMP_DUST (shared.AssetLibrary_JUMP_DUST) package shared { import mx.core.*; public class AssetLibrary_JUMP_DUST extends BitmapAsset { } }//package shared
Section 300
//AssetLibrary_JUMPING_NINJA (shared.AssetLibrary_JUMPING_NINJA) package shared { import mx.core.*; public class AssetLibrary_JUMPING_NINJA extends BitmapAsset { } }//package shared
Section 301
//AssetLibrary_KANJI_ATTACK (shared.AssetLibrary_KANJI_ATTACK) package shared { import mx.core.*; public class AssetLibrary_KANJI_ATTACK extends BitmapAsset { } }//package shared
Section 302
//AssetLibrary_KANJI_NINJA (shared.AssetLibrary_KANJI_NINJA) package shared { import mx.core.*; public class AssetLibrary_KANJI_NINJA extends BitmapAsset { } }//package shared
Section 303
//AssetLibrary_KANJI_RAT (shared.AssetLibrary_KANJI_RAT) package shared { import mx.core.*; public class AssetLibrary_KANJI_RAT extends BitmapAsset { } }//package shared
Section 304
//AssetLibrary_LASER (shared.AssetLibrary_LASER) package shared { import mx.core.*; public class AssetLibrary_LASER extends BitmapAsset { } }//package shared
Section 305
//AssetLibrary_LASER_NINJA (shared.AssetLibrary_LASER_NINJA) package shared { import mx.core.*; public class AssetLibrary_LASER_NINJA extends BitmapAsset { } }//package shared
Section 306
//AssetLibrary_LEONARDO (shared.AssetLibrary_LEONARDO) package shared { import mx.core.*; public class AssetLibrary_LEONARDO extends BitmapAsset { } }//package shared
Section 307
//AssetLibrary_LEONARDO_TILE (shared.AssetLibrary_LEONARDO_TILE) package shared { import mx.core.*; public class AssetLibrary_LEONARDO_TILE extends BitmapAsset { } }//package shared
Section 308
//AssetLibrary_LEONARDO_TRAIL (shared.AssetLibrary_LEONARDO_TRAIL) package shared { import mx.core.*; public class AssetLibrary_LEONARDO_TRAIL extends BitmapAsset { } }//package shared
Section 309
//AssetLibrary_LEVEL_CHECKMARK (shared.AssetLibrary_LEVEL_CHECKMARK) package shared { import mx.core.*; public class AssetLibrary_LEVEL_CHECKMARK extends BitmapAsset { } }//package shared
Section 310
//AssetLibrary_LEVEL_LOCK (shared.AssetLibrary_LEVEL_LOCK) package shared { import mx.core.*; public class AssetLibrary_LEVEL_LOCK extends BitmapAsset { } }//package shared
Section 311
//AssetLibrary_LEVEL_MARKERS (shared.AssetLibrary_LEVEL_MARKERS) package shared { import mx.core.*; public class AssetLibrary_LEVEL_MARKERS extends BitmapAsset { } }//package shared
Section 312
//AssetLibrary_MICHELANGELO (shared.AssetLibrary_MICHELANGELO) package shared { import mx.core.*; public class AssetLibrary_MICHELANGELO extends BitmapAsset { } }//package shared
Section 313
//AssetLibrary_MICHELANGEO_TRAIL (shared.AssetLibrary_MICHELANGEO_TRAIL) package shared { import mx.core.*; public class AssetLibrary_MICHELANGEO_TRAIL extends BitmapAsset { } }//package shared
Section 314
//AssetLibrary_MOUSER (shared.AssetLibrary_MOUSER) package shared { import mx.core.*; public class AssetLibrary_MOUSER extends BitmapAsset { } }//package shared
Section 315
//AssetLibrary_MUTE_BUTTON (shared.AssetLibrary_MUTE_BUTTON) package shared { import mx.core.*; public class AssetLibrary_MUTE_BUTTON extends BitmapAsset { } }//package shared
Section 316
//AssetLibrary_OOZE_CAN (shared.AssetLibrary_OOZE_CAN) package shared { import mx.core.*; public class AssetLibrary_OOZE_CAN extends BitmapAsset { } }//package shared
Section 317
//AssetLibrary_OOZE_CANNISTER (shared.AssetLibrary_OOZE_CANNISTER) package shared { import mx.core.*; public class AssetLibrary_OOZE_CANNISTER extends BitmapAsset { } }//package shared
Section 318
//AssetLibrary_PACKSHOT_LARGE (shared.AssetLibrary_PACKSHOT_LARGE) package shared { import mx.core.*; public class AssetLibrary_PACKSHOT_LARGE extends BitmapAsset { } }//package shared
Section 319
//AssetLibrary_PACKSHOT_SMALL (shared.AssetLibrary_PACKSHOT_SMALL) package shared { import mx.core.*; public class AssetLibrary_PACKSHOT_SMALL extends BitmapAsset { } }//package shared
Section 320
//AssetLibrary_PANEL (shared.AssetLibrary_PANEL) package shared { import mx.core.*; public class AssetLibrary_PANEL extends BitmapAsset { } }//package shared
Section 321
//AssetLibrary_PIZZA (shared.AssetLibrary_PIZZA) package shared { import mx.core.*; public class AssetLibrary_PIZZA extends BitmapAsset { } }//package shared
Section 322
//AssetLibrary_PLATFORM (shared.AssetLibrary_PLATFORM) package shared { import mx.core.*; public class AssetLibrary_PLATFORM extends BitmapAsset { } }//package shared
Section 323
//AssetLibrary_PORTRAIT_CASEY_JONES (shared.AssetLibrary_PORTRAIT_CASEY_JONES) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_CASEY_JONES extends BitmapAsset { } }//package shared
Section 324
//AssetLibrary_PORTRAIT_DONATELLO (shared.AssetLibrary_PORTRAIT_DONATELLO) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_DONATELLO extends BitmapAsset { } }//package shared
Section 325
//AssetLibrary_PORTRAIT_LEONARDO (shared.AssetLibrary_PORTRAIT_LEONARDO) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_LEONARDO extends BitmapAsset { } }//package shared
Section 326
//AssetLibrary_PORTRAIT_MICHELANGELO (shared.AssetLibrary_PORTRAIT_MICHELANGELO) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_MICHELANGELO extends BitmapAsset { } }//package shared
Section 327
//AssetLibrary_PORTRAIT_PIZZA_DUDE (shared.AssetLibrary_PORTRAIT_PIZZA_DUDE) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_PIZZA_DUDE extends BitmapAsset { } }//package shared
Section 328
//AssetLibrary_PORTRAIT_RAPHAEL (shared.AssetLibrary_PORTRAIT_RAPHAEL) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_RAPHAEL extends BitmapAsset { } }//package shared
Section 329
//AssetLibrary_PORTRAIT_SPLINTER (shared.AssetLibrary_PORTRAIT_SPLINTER) package shared { import mx.core.*; public class AssetLibrary_PORTRAIT_SPLINTER extends BitmapAsset { } }//package shared
Section 330
//AssetLibrary_PUT_THIS_GAME (shared.AssetLibrary_PUT_THIS_GAME) package shared { import mx.core.*; public class AssetLibrary_PUT_THIS_GAME extends BitmapAsset { } }//package shared
Section 331
//AssetLibrary_RAPHAEL (shared.AssetLibrary_RAPHAEL) package shared { import mx.core.*; public class AssetLibrary_RAPHAEL extends BitmapAsset { } }//package shared
Section 332
//AssetLibrary_RAPHAEL_TRAIL (shared.AssetLibrary_RAPHAEL_TRAIL) package shared { import mx.core.*; public class AssetLibrary_RAPHAEL_TRAIL extends BitmapAsset { } }//package shared
Section 333
//AssetLibrary_ROOF_TILESET (shared.AssetLibrary_ROOF_TILESET) package shared { import mx.core.*; public class AssetLibrary_ROOF_TILESET extends BitmapAsset { } }//package shared
Section 334
//AssetLibrary_ROOF_TOP_EDGE (shared.AssetLibrary_ROOF_TOP_EDGE) package shared { import mx.core.*; public class AssetLibrary_ROOF_TOP_EDGE extends BitmapAsset { } }//package shared
Section 335
//AssetLibrary_ROOF_WALL (shared.AssetLibrary_ROOF_WALL) package shared { import mx.core.*; public class AssetLibrary_ROOF_WALL extends BitmapAsset { } }//package shared
Section 336
//AssetLibrary_ROOF_WALL_SLICK (shared.AssetLibrary_ROOF_WALL_SLICK) package shared { import mx.core.*; public class AssetLibrary_ROOF_WALL_SLICK extends BitmapAsset { } }//package shared
Section 337
//AssetLibrary_ROOFTOP_STATIC_BG (shared.AssetLibrary_ROOFTOP_STATIC_BG) package shared { import mx.core.*; public class AssetLibrary_ROOFTOP_STATIC_BG extends BitmapAsset { } }//package shared
Section 338
//AssetLibrary_SENTRY (shared.AssetLibrary_SENTRY) package shared { import mx.core.*; public class AssetLibrary_SENTRY extends BitmapAsset { } }//package shared
Section 339
//AssetLibrary_SHELL_CELL (shared.AssetLibrary_SHELL_CELL) package shared { import mx.core.*; public class AssetLibrary_SHELL_CELL extends BitmapAsset { } }//package shared
Section 340
//AssetLibrary_SHREDDER (shared.AssetLibrary_SHREDDER) package shared { import mx.core.*; public class AssetLibrary_SHREDDER extends BitmapAsset { } }//package shared
Section 341
//AssetLibrary_SHURIKEN (shared.AssetLibrary_SHURIKEN) package shared { import mx.core.*; public class AssetLibrary_SHURIKEN extends BitmapAsset { } }//package shared
Section 342
//AssetLibrary_SHURIKEN_NINJA (shared.AssetLibrary_SHURIKEN_NINJA) package shared { import mx.core.*; public class AssetLibrary_SHURIKEN_NINJA extends BitmapAsset { } }//package shared
Section 343
//AssetLibrary_SIGN_BUBBLE (shared.AssetLibrary_SIGN_BUBBLE) package shared { import mx.core.*; public class AssetLibrary_SIGN_BUBBLE extends BitmapAsset { } }//package shared
Section 344
//AssetLibrary_SLOTH (shared.AssetLibrary_SLOTH) package shared { import mx.core.*; public class AssetLibrary_SLOTH extends BitmapAsset { } }//package shared
Section 345
//AssetLibrary_SPECIAL_CASEY_JONES (shared.AssetLibrary_SPECIAL_CASEY_JONES) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_CASEY_JONES extends BitmapAsset { } }//package shared
Section 346
//AssetLibrary_SPECIAL_DONATELLO (shared.AssetLibrary_SPECIAL_DONATELLO) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_DONATELLO extends BitmapAsset { } }//package shared
Section 347
//AssetLibrary_SPECIAL_LEONARDO (shared.AssetLibrary_SPECIAL_LEONARDO) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_LEONARDO extends BitmapAsset { } }//package shared
Section 348
//AssetLibrary_SPECIAL_MICHELANGELO (shared.AssetLibrary_SPECIAL_MICHELANGELO) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_MICHELANGELO extends BitmapAsset { } }//package shared
Section 349
//AssetLibrary_SPECIAL_PIZZA_DELIVERY (shared.AssetLibrary_SPECIAL_PIZZA_DELIVERY) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_PIZZA_DELIVERY extends BitmapAsset { } }//package shared
Section 350
//AssetLibrary_SPECIAL_RAPHAEL (shared.AssetLibrary_SPECIAL_RAPHAEL) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_RAPHAEL extends BitmapAsset { } }//package shared
Section 351
//AssetLibrary_SPECIAL_SPLINTER (shared.AssetLibrary_SPECIAL_SPLINTER) package shared { import mx.core.*; public class AssetLibrary_SPECIAL_SPLINTER extends BitmapAsset { } }//package shared
Section 352
//AssetLibrary_STREET_STATIC_BG (shared.AssetLibrary_STREET_STATIC_BG) package shared { import mx.core.*; public class AssetLibrary_STREET_STATIC_BG extends BitmapAsset { } }//package shared
Section 353
//AssetLibrary_STREETS_TILESET (shared.AssetLibrary_STREETS_TILESET) package shared { import mx.core.*; public class AssetLibrary_STREETS_TILESET extends BitmapAsset { } }//package shared
Section 354
//AssetLibrary_SUPER_SHREDDER (shared.AssetLibrary_SUPER_SHREDDER) package shared { import mx.core.*; public class AssetLibrary_SUPER_SHREDDER extends BitmapAsset { } }//package shared
Section 355
//AssetLibrary_SWITCH (shared.AssetLibrary_SWITCH) package shared { import mx.core.*; public class AssetLibrary_SWITCH extends BitmapAsset { } }//package shared
Section 356
//AssetLibrary_TITLE_LOGO (shared.AssetLibrary_TITLE_LOGO) package shared { import mx.core.*; public class AssetLibrary_TITLE_LOGO extends BitmapAsset { } }//package shared
Section 357
//AssetLibrary_UBISOFT_LOGO (shared.AssetLibrary_UBISOFT_LOGO) package shared { import mx.core.*; public class AssetLibrary_UBISOFT_LOGO extends BitmapAsset { } }//package shared
Section 358
//AssetLibrary_URBANSQUALL_BUTTON (shared.AssetLibrary_URBANSQUALL_BUTTON) package shared { import mx.core.*; public class AssetLibrary_URBANSQUALL_BUTTON extends BitmapAsset { } }//package shared
Section 359
//AssetLibrary_WAREHOUSE_TILESET (shared.AssetLibrary_WAREHOUSE_TILESET) package shared { import mx.core.*; public class AssetLibrary_WAREHOUSE_TILESET extends BitmapAsset { } }//package shared
Section 360
//Constants (shared.Constants) package shared { public class Constants { public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_DONATELLO:String = "Damages all enemies. Extra damage to Machines."; public static const DATA_EDGES_VERTICAL_NONE:String = "j"; public static const CORNER_TYPE_DOOR_DOOR:int = 4; public static const UNLOCK_ALL:Boolean = false; public static const LEFT:int = 2; public static const ENTITY_TYPE_DART:String = "dart"; public static const CHARACTER_LEONARDO:String = "Leonardo"; public static const DATA_EDGES_HORIZONTAL_DOOR:String = "i"; public static const ENTITY_TYPE_SHURIKEN:String = "aaX"; public static const DAMAGE_RAPHAEL:int = 115; public static const ROOM_TYPE_LIVING_ROOM:int = 2; public static const CHARACTER_ATTACK_DESCRIPTION_LEONARDO:String = "Effective against Foot Clan. Weapon has long range."; public static const ENTITY_TYPE_SPAWNER:String = "spawner"; public static const CORNER_TYPE_DOOR_WALL:int = 3; public static const DATA_ROOM_COL_COUNT:String = "d"; public static const ENTITY_TYPE_SUPER_SHREDDER:String = "super_shredder"; public static const CHARACTER_ATTACK_DESCRIPTION_DONATELLO:String = "Effective against Machines. Weapon has long range."; public static const LITE_VERSION:Boolean = false; public static const ENTITY_TYPE_SENTRY:String = "_sentry"; public static const ENTITY_TYPE_JUGGERNAUGHT:String = "_juggernaught"; public static const DATA_SELECTED_PRIMARY:String = "selected_primary"; public static const SCORE_MODIFIER_BRONZE:Number = 0.85; public static const POINTS_FOR_TIME_BONUS:int = 20; public static const EXTERNAL_DISABLE_TRACKING:int = 16; public static const DATA_ROOM_COUNT:String = "a"; public static const CHARACTER_DONATELLO:String = "Donatello"; public static const CORNER_TYPE_NONE_NONE:int = 8; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_SPLINTER:String = "Devastating damage to all enemies."; public static const CHARACTER_SPECIAL_USAGE_RAPHAEL:int = 7; public static const CHARACTER_SPECIAL_USAGE_MICHELANGELO:int = 7; public static const DATA_SCORE_TO_BEAT:String = "l"; public static const CHARACTER_ATTACK_DESCRIPTION_MICHELANGELO:String = "Effective against Machines. Weapon deals extra damage."; public static const ROOM_TYPE_KITCHEN:int = 1; public static const ENTITY_TYPE_SPECIAL_MICHELANGELO:String = "special_michael"; public static const DAMAGE_LEONARDO:int = 100; public static const DATA_EDGES_VERTICAL_DOOR:String = "k"; public static const ENTITY_TYPE_NOTE:String = "note"; public static const ENTITY_TYPE_PLATFORM:String = "platform"; public static const ENTITY_TYPE_SHREDDER:String = "_shredder"; public static const ENTITY_TYPE_CLONE_SHREDDER:String = "clone_shredder"; public static const ENTITY_TYPE_FULL_PIZZA:String = "_full_pizza"; public static const ENTITY_TYPE_SPECIAL_SPLINTER:String = "special_splinter"; public static const ENTITY_TYPE_OOZE_CAN:String = "_ooze_can"; public static const ROOM_CONTAINER_X:int = 56; public static const ROOM_CONTAINER_Y:int = 74; public static const ENTITY_TYPE_SPECIAL_PIZZA_DELIVERY:String = "special_pizza_delivery"; public static const UP:int = 0; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_PIZZA_DUDE:String = "Restores health by delivering pizza to player."; public static const ENTITY_TYPE_SLOTH:String = "_sloth"; public static const DOWN:int = 1; public static const INVINCIBILITY_TIME:int = 1600; public static const ATTACK_MULTIPLIER_STRONG:Number = 1.2; public static const ENTITY_TYPE_BLOWGUN_NINJA:String = "_blowgun_ninja"; public static const ENTITY_TYPE_MOUSER:String = "_mouser"; public static const CORNER_TYPE_NONE_DOOR:int = 7; public static const ENTITY_TYPE_COMBAT_WAVE:String = "combat_wave"; public static const ENTITY_TYPE_DRILL_BOX:String = "drill_box"; public static const ROOM_TYPE_STORAGE_ROOM:int = 3; public static const POINTS_FOR_MOONROCKS:int = 500; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_MICHELANGELO:String = "Damages enemies directly in attack path. Extra damage to Machines."; public static const UBI_SITE_LINK:String = "http://tmntgame.us.ubi.com/?utm_source=partnersites&utm_medium=flashgame&utm_campaign=tmnt"; public static const DAMAGE_MICHELANGELO:int = 115; public static const ENTITY_TYPE_JUMPING_NINJA:String = "_jumping_ninja"; public static const ENTITY_TYPE_BREAKABLE_WALL:String = "breakable_wall"; public static const ENTITY_TYPE_CRUMBLING_BLOCK:String = "crumbling_block"; public static const ENEMY_GROUP_FILTER:int = -5; public static const ENTITY_TYPE_SWORD_NINJA:String = "_sword_ninja"; public static const DATA_ROOM_STYLE:String = "f"; public static const CORNER_TYPE_NONE_WALL:int = 6; public static const EXTERNAL_STATUS:int = 0; public static const MUSIC_ENABLED:Boolean = !(ALLOW_DEBUG); public static const CHARACTER_SPECIAL_USAGE_LEONARDO:int = 7; public static const EXTERNAL_DISABLE_CREDITS_AND_TRACKING:int = (EXTERNAL_DISABLE_CREDITS | EXTERNAL_DISABLE_TRACKING); public static const DATA_ROOM_COL:String = "b"; public static const TILE_SIZE:int = 24; public static const DATA_ROOM_ROW_COUNT:String = "e"; public static const ENTITY_TYPE_PIZZA:String = "_pizza"; public static const CORNER_TYPE_WALL_NONE:int = 2; public static const CHARACTER_SPLINTER:String = "Splinter"; public static const DATA_LEVEL_INDEX:String = "level_index"; public static const MAX_COLS:int = 22; public static const ENTITY_TYPE_SPECIAL_RAPHAEL:String = "special_raphael"; public static const ENTITY_TYPE_SHURIKEN_NINJA:String = "_shuriken_ninja"; public static const COMBO_TIMER:Number = 2000; public static const EXTERNAL_DISABLE_ALL:int = (EXTERNAL_DISABLE_CREDITS_AND_TRACKING | EXTERNAL_DISABLE_LINKS); public static const ENTITY_TYPE_DONATELLO:String = "bd"; public static const EDGE_TYPE_NONE:int = 2; public static const LEVEL_DESCRIPTIONS:Array = [{title:"Turtle Power", description:"The Teenage Mutant Ninja Turtles head out to save their friend April."}, {title:"City Beatdown", description:"The Foot have kidnapped April! The fight to rescue her is on!"}, {title:"Urban Brawl", description:"It's an ambush!"}, {title:"Foot Patrol", description:"The Turtles continue to hunt down the Foot to save April."}, {title:"Enter the Hun", description:"The Hun tries to take down the Turtles"}, {title:"Downtown Throwdown", description:"Foot Soldiers and Flying Drones... this is getting complicated."}, {title:"Rooftop Rumble", description:"The Foot take to the rooftops trying to lose the Turtle's pursuit."}, {title:"Highrise Havoc", description:"The Foot are everywhere! The Turtles will need to fight them off."}, {title:"Platform Peril", description:"Where are the Foot taking April? What did she find that they need to protect so fiercely?"}, {title:"Shredded", description:"The Turtles are attacked by their arch-nemesis!"}, {title:"Shady Dealings", description:"The Foot are up to something in that warehouse..."}, {title:"Trouble Brewing", description:"It looks like the Foot have been conducting experiments... but why?"}, {title:"Warehouse Warfare", description:"This place is crawling with Foot Soldiers and Robots, there must be something big here."}, {title:"Shellshock", description:"They've got to be running out of Foot soldiers. The end is near."}, {title:"Shredder's Revenge", description:"Shredder is back and more powerful than ever! So that's what they were doing in the lab..."}]; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_CASEY_JONES:String = "Deal large damage to enemies directly in attack path."; public static const ENTITY_TYPE_LASER_NINJA:String = "_laser_ninja"; public static const DAMAGE_DONATELLO:int = 100; public static const ENTITY_TYPE_SPECIAL_CASEY_JONES:String = "special_casey_jones"; public static const ENTITY_TYPE_HUN:String = "hun"; public static const STARTING_HEALTH:int = 20; public static const CHARACTER_PIZZA_DUDE:String = "Pizza Delivery Guy"; public static const CHARACTER_SPECIAL_USAGE_PIZZA_DUDE:int = 12; public static const ATTACK_MULTIPLIER_WEAK:Number = 0.8; public static const DATA_ROOM_PACKED:String = "g"; public static const ENTITY_TYPE_LASER:String = "_aaY"; public static const DATA_ROOM_ROW:String = "c"; public static const ROOM_TYPE_BATHROOM:int = 0; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_LEONARDO:String = "Damages all enemies. Extra damage to Foot Clan."; public static const CHARACTER_CASEY_JONES:String = "Casey Jones"; public static const ENTITY_TYPE_ROOM:String = "s"; public static const COMBAT_WAVE_BOUNDARY_COLLISION_CATEGORY:int = 4; public static const CORNER_TYPE_WALL_DOOR:int = 1; public static const CHARACTER_SPECIAL_ATTACK_DESCRIPTION_RAPHAEL:String = "Damages enemies directly in attack path. Extra damage to Foot Clan."; public static const EDGE_TYPE_COUNT:int = 3; public static const ENTITY_TYPE_ACID_POOL:String = "_acid_pool"; public static const ENTITY_TYPE_ELECTRICAL_WALL:String = "electrical_wall"; public static const CHARACTER_MICHELANGELO:String = "Michelangelo"; public static const ENTITY_TYPE_SWITCH:String = "_switch"; public static const ENTITY_TYPE_MICHELANGELO:String = "bm"; public static const ENTITY_DEFAULT_RENDER_LAYER:int = 50; public static const CORNER_TYPE_WALL_WALL:int = 0; public static const DATA_SELECTED_SECONDARY:String = "selected_secondary"; public static const CORNER_TYPE_DOOR_NONE:int = 5; public static const EXTERNAL_DISABLE_CREDITS:int = 1; public static const EDGE_TYPE_DOOR:int = 1; public static const STARTING_CHARGE:int = 30; public static const DATA_EDGES_HORIZONTAL_NONE:String = "h"; public static const DATA_TUTORIAL_TEXT:String = "tute_text"; public static const ALLOW_DEBUG:Boolean = false; public static const UBI_BUY_NOW_LINK:String = "http://tmntgame.us.ubi.com/?utm_source=partnersites&utm_medium=flashgame&utm_campaign=tmnt"; public static const ENTITY_TYPE_LEONARDO:String = "b"; public static const ROOM_TYPE_COUNT:int = 4; public static const ENTITY_TYPE_EXIT:String = "t"; public static const PLAYER_COLLISION_CATEGORY:int = 2; public static const PUT_THIS_GAME_ON_YOUR_SITE_LINK:String = "http://static2.cdn.ubi.com/ncsa/TMNT/mini-game/minigame.zip"; public static const CHARACTER_RAPHAEL:String = "Raphael"; public static const EDGE_TYPE_WALL:int = 0; public static const ENTITY_TYPE_SWORD_NINJA_PASSIVE:String = "_sword_ninja_passive"; public static const SCORE_MODIFIER_SILVER:Number = 0.9; public static const ENTITY_TYPE_RAPHAEL:String = "br"; public static const SCORE_MODIFIER_GOLD:Number = 0.95; public static const RENDER_WIDTH:int = 660; public static const ENTITY_TYPE_LINEAR_SENTRY:String = "_linear_sentry"; public static const CORNER_TYPE_COUNT:int = 9; public static const ENTITY_TYPE_OOZE_CANNISTER:String = "_ooze_cannister"; public static const POINTS_FOR_BREAKING_SOMETHING:int = 100; public static const DATA_TUTORIAL_SEPARATOR:String = "#####"; public static const ENTITY_TYPE_ANGRY_SENTRY:String = "_angry_sentry"; public static const CHARACTER_SPECIAL_USAGE_SPLINTER:int = 12; public static const CHARACTER_SPECIAL_USAGE_DONATELLO:int = 7; public static const RENDER_HEIGHT:int = 420; public static const MAX_ROWS:int = 17; public static const EXTERNAL_DISABLE_LINKS:int = 0x0100; public static const EXTERNAL_ALLOW_ALL:int = 0; public static const RIGHT:int = 3; public static const CHARACTER_ATTACK_DESCRIPTION_RAPHAEL:String = "Effective against Foot Clan. Weapon deals extra damage."; public static const CHARACTER_SPECIAL_USAGE_CASEY_JONES:int = 10; public function Constants(){ super(); } } }//package shared
Section 361
//DefaultTextField (shared.DefaultTextField) package shared { import flash.text.*; public class DefaultTextField extends TextField { private static const us_customFont:String = "DefaultTextField_us_customFont"; public function DefaultTextField(a_text:String="", a_color:uint=0xFFFFFF, a_size:int=22, a_fontName:String="us_customFont"){ super(); this.autoSize = TextFieldAutoSize.LEFT; this.selectable = false; this.embedFonts = true; this.defaultTextFormat = new TextFormat(a_fontName, a_size, a_color, null, null, null, null, null, null, null, null, null, -2); this.text = a_text; } public function get size():int{ return ((this.defaultTextFormat.size as int)); } public function set size(a_size:int):void{ var f:TextFormat = copyTextFormat(); f.size = a_size; this.defaultTextFormat = f; } public function underline():void{ var f:TextFormat = copyTextFormat(); f.underline = true; this.defaultTextFormat = f; } public function center():void{ var f:TextFormat = copyTextFormat(); f.align = TextFormatAlign.CENTER; this.defaultTextFormat = f; this.text = this.text; } private function copyTextFormat():TextFormat{ var f:TextFormat = this.defaultTextFormat; f = new TextFormat(f.font, f.size, f.color, f.bold, f.italic, f.underline, f.url, f.target, f.align, f.leftMargin, f.rightMargin, f.indent, f.leading); return (f); } public function set leading(a_val:int):void{ var f:TextFormat = copyTextFormat(); f.leading = a_val; this.defaultTextFormat = f; } public function right():void{ var f:TextFormat = copyTextFormat(); f.align = TextFormatAlign.RIGHT; this.defaultTextFormat = f; this.text = this.text; } } }//package shared
Section 362
//DefaultTextField_us_customFont (shared.DefaultTextField_us_customFont) package shared { import mx.core.*; public class DefaultTextField_us_customFont extends FontAsset { } }//package shared
Section 363
//LevelBackground (shared.LevelBackground) package shared { import flash.display.*; import flash.geom.*; public class LevelBackground extends Sprite { private var m_levelBounds:Rectangle; private var m_type:String;// = "none" private var m_limitY:Number; private var m_scrollableBackground:DisplayObject; private var m_staticBackground:Sprite; private var m_scrollingContainer:Sprite; public static const STREET:String = "street"; public static const NONE:String = "none"; public static const ROOF_TOPS:String = "rooftops"; public function LevelBackground(a_type:String, a_limitY:Number){ var bgClass:Class; super(); m_limitY = (a_limitY - (Constants.RENDER_HEIGHT / 2)); m_type = a_type; if (m_type == NONE){ return; }; var fillColor:uint; if (m_type == STREET){ fillColor = 10116216; bgClass = AssetLibrary.STREET_STATIC_BG; } else { fillColor = 1517339; bgClass = AssetLibrary.ROOFTOP_STATIC_BG; }; m_staticBackground = new Sprite(); m_staticBackground.graphics.beginFill(fillColor); m_staticBackground.graphics.drawRect(0, 0, Constants.RENDER_WIDTH, Constants.RENDER_HEIGHT); addChild(m_staticBackground); m_scrollingContainer = new Sprite(); addChild(m_scrollingContainer); m_scrollableBackground = new (bgClass); m_scrollableBackground.x = ((Constants.RENDER_WIDTH / 2) - (m_scrollableBackground.width / 2)); m_scrollingContainer.addChild(m_scrollableBackground); } public function update(a_viewX:Number, a_viewY:Number):void{ if (m_type == NONE){ return; }; if (a_viewY > m_limitY){ a_viewY = m_limitY; }; m_scrollingContainer.y = (-(a_viewY) + (Constants.RENDER_HEIGHT / 2)); } public function setBounds(a_x:Number, a_y:Number, a_width:Number, a_height:Number):void{ if (m_type == NONE){ return; }; m_levelBounds = new Rectangle(a_x, a_y, a_width, a_height); var maxY:Number = (m_levelBounds.bottom - m_scrollableBackground.height); m_scrollableBackground.y = maxY; } } }//package shared
Section 364
//LevelData (shared.LevelData) package shared { import flash.utils.*; import game.*; public class LevelData { private static var s_index:int = 0; private static var s_levels:Dictionary = null; public function LevelData(){ super(); } private static function init():void{ if (s_levels != null){ return; }; s_levels = new Dictionary(); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL1)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL2)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL3)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL4)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL5)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL6)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL7)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL8)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL9)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL10)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL11)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL12)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL13)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL14)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL15)); writeLevel(s_index++, LevelXMLs.parseXML(LevelXMLs.LEVEL16)); //unresolved jump var _slot1 = e; throw (new Error((("XML Parse error [" + s_index) + "]"))); } public static function writeLevel(a_levelIndex:int, a_value:XML):void{ s_levels[a_levelIndex] = a_value; } public static function readLevel(a_levelIndex:int):XML{ if (s_levels == null){ init(); }; if (s_levels[a_levelIndex] == null){ return (null); }; return (s_levels[a_levelIndex]); } } }//package shared
Section 365
//PlayerAttackBoxes (shared.PlayerAttackBoxes) package shared { import flash.geom.*; public class PlayerAttackBoxes { public var crouch:Rectangle; public var combo1:Rectangle; public var combo2:Rectangle; public var combo3:Rectangle; public var air:Rectangle; public function PlayerAttackBoxes(){ super(); } } }//package shared
Section 366
//RoofTileset (shared.RoofTileset) package shared { import flash.display.*; import com.urbansquall.display.*; public class RoofTileset extends TileSet { private static var s_instance:RoofTileset; public function RoofTileset(){ s_instance = this; var bitmapData:BitmapData = (new AssetLibrary.ROOF_TILESET() as Bitmap).bitmapData; super("roof", 32, 32, bitmapData); assignNameToNextTile("roof_top_edge_1"); assignNameToNextTile("roof_top_edge_2"); assignNameToNextTile("roof_top_edge_3"); assignNameToNextTile("roof_top_edge_4"); assignNameToNextTile("roof_top_edge_5"); assignNameToNextTile("roof_none_1"); assignNameToNextTile("roof_none_2"); assignNameToNextTile("roof_none_3"); assignNameToNextTile("roof_none_4"); assignNameToNextTile("roof_none_5"); assignNameToNextTile("roof_none_6"); assignNameToNextTile("roof_pizza_1"); assignNameToNextTile("roof_pizza_2"); assignNameToNextTile("roof_pizza_3"); assignNameToNextTile("roof_top_1"); assignNameToNextTile("roof_top_2"); assignNameToNextTile("roof_top_exhaust"); assignNameToNextTile("roof_top_3"); assignNameToNextTile("roof_top_4"); assignNameToNextTile("roof_top_edge_left"); assignNameToNextTile("roof_top_debris_1"); assignNameToNextTile("roof_top_debris_2"); assignNameToNextTile("roof_lamp_top"); assignNameToNextTile("roof_ramp_top"); assignNameToNextTile("roof_ramp_end_left"); assignNameToNextTile("roof_pizza_4"); assignNameToNextTile("roof_pizza_5"); assignNameToNextTile("roof_pizza_6"); assignNameToNextTile("roof_bottom_1"); assignNameToNextTile("roof_bottom_2"); assignNameToNextTile("roof_bottom_ladder"); assignNameToNextTile("roof_bottom_3"); assignNameToNextTile("roof_bottom_4"); assignNameToNextTile("roof_ladder"); assignNameToNextTile("roof_broken_window_1"); assignNameToNextTile("roof_broker_window_2"); assignNameToNextTile("roof_lamp_middle"); assignNameToNextTile("roof_ramp_bottom"); assignNameToNextTile("roof_ramp_end_right"); assignNameToNextTile("roof_NONONENEONEONEONE"); assignNameToNextTile("roof_NONEOENOENNNNENEN"); assignNameToNextTile("roof_NONENENENENENNNNE"); assignNameToNextTile("roof_wall_end_left_1"); assignNameToNextTile("roof_wall_end_dirt_1"); assignNameToNextTile("roof_wall_1"); assignNameToNextTile("roof_wall_2"); assignNameToNextTile("roof_wall_end_right_1"); assignNameToNextTile("roof_window_left"); assignNameToNextTile("roof_window_top"); assignNameToNextTile("roof_window_right"); assignNameToNextTile("roof_lamp_bottom"); assignNameToNextTile("roof_wood_half_top"); assignNameToNextTile("roof_wood_full_top"); assignNameToNextTile("roof_NONONENEONEONEONE123asas"); assignNameToNextTile("roof_NONEOENOENNNNENEN44234dfas"); assignNameToNextTile("roof_NONENENENENENNNNE65465asdddda"); assignNameToNextTile("roof_wall_end_left_2"); assignNameToNextTile("roof_wall_end_dirt_2"); assignNameToNextTile("roof_wall_3"); assignNameToNextTile("roof_wall_4"); assignNameToNextTile("roof_wall_end_right_2"); assignNameToNextTile("roof_window_bottom_left"); assignNameToNextTile("roof_window_bottom"); assignNameToNextTile("roof_window_bottom_right"); assignNameToNextTile("roof_wood_bottom_1"); assignNameToNextTile("roof_wood_bottom_2"); assignNameToNextTile("roof_wood_bottom_3"); assignNameToNextTile("roof_NONONENEONEONEONE123asda"); assignNameToNextTile("roof_NONEOENOENNNNENEN44234asd"); assignNameToNextTile("roof_NONENENENENENNNNE65465dasad"); } public static function get instance():RoofTileset{ return (s_instance); } } }//package shared
Section 367
//SoundCache (shared.SoundCache) package shared { import flash.media.*; public class SoundCache { public static var oozeSound:Sound; public static var footSoldierHit1:Sound; public static var footSoldierHit2:Sound; public static var footSoldierHit3:Sound; public static var robotHit1:Sound; public static var shurikenSound:Sound; public static var sentryActivateSound:Sound; public function SoundCache(){ super(); } public static function init():void{ shurikenSound = new ShurikenBlowDartThrowNoise1(); oozeSound = new GainingOozeNoise2(); sentryActivateSound = new SentryActivate(); footSoldierHit1 = new FootSoldierHit(); footSoldierHit2 = new FootSoldierHit2(); footSoldierHit3 = new FootSoldierHit3(); robotHit1 = new HitNoiseForRobots1(); } } }//package shared
Section 368
//Story (shared.Story) package shared { import flash.utils.*; public class Story { private var m_position:int;// = 0 private var m_x:int; private var m_y:int; private var m_movieClipClass:String;// = null private var m_levelNum:int;// = 0 private var m_wasForcedToPlay:Boolean;// = false public function Story(a_levelNum:int, a_x:int, a_y:int, a_movieClipClass:String){ super(); m_levelNum = a_levelNum; m_x = a_x; m_y = a_y; m_movieClipClass = a_movieClipClass; } public function get levelNum():int{ return (m_levelNum); } public function get x():int{ return (m_x); } public function get wasForcedToPlay():Boolean{ return (m_wasForcedToPlay); } public function forcePlay():void{ m_wasForcedToPlay = true; } public function get movieClipClass():Class{ var mcClass:Class; mcClass = (getDefinitionByName(m_movieClipClass) as Class); //unresolved jump var _slot1 = e; return (null); return (mcClass); } public function get y():int{ return (m_y); } } }//package shared
Section 369
//StoryData (shared.StoryData) package shared { public class StoryData { private var m_stories:Array; private var m_forceCompilation:Array; public function StoryData(){ m_stories = new Array(); m_forceCompilation = [tmnt_page01_mc, tmnt_page02_mc, tmnt_page04_mc, tmnt_page02b_mc]; super(); addStory(1, 25, 41, "tmnt_page01_mc"); addStory(5, 259, 56, "tmnt_page02_mc"); addStory(10, 241, 297, "tmnt_page02b_mc"); addStory(16, 619, 384, "tmnt_page04_mc"); } public function get stories():Array{ return (m_stories); } private function addStory(a_levelNum:int, a_x:int, a_y:int, a_movieClipClass:String):void{ var story:Story = new Story(a_levelNum, a_x, a_y, a_movieClipClass); m_stories.push(story); } } }//package shared
Section 370
//StreetTileset (shared.StreetTileset) package shared { import flash.display.*; import com.urbansquall.display.*; public class StreetTileset extends TileSet { private static var s_instance:StreetTileset; public function StreetTileset(){ s_instance = this; var bitmapData:BitmapData = (new AssetLibrary.STREETS_TILESET() as Bitmap).bitmapData; super("street", 32, 32, bitmapData); assignNameToNextTile("street_top_edge_1"); assignNameToNextTile("street_top_edge_2"); assignNameToNextTile("street_top_edge_3"); assignNameToNextTile("street_top_edge_4"); assignNameToNextTile("street_top_edge_5"); assignNameToNextTile("street_pole_1"); assignNameToNextTile("street_pole_2"); assignNameToNextTile("street_pole_3"); assignNameToNextTile("street_none_4"); assignNameToNextTile("street_none_5"); assignNameToNextTile("street_none_6"); assignNameToNextTile("street_none_7"); assignNameToNextTile("street_none_8"); assignNameToNextTile("street_SOLID_floor"); assignNameToNextTile("street_top_edge_left"); assignNameToNextTile("street_top_1"); assignNameToNextTile("street_top_exhaust"); assignNameToNextTile("street_top_2"); assignNameToNextTile("street_top_edge_right"); assignNameToNextTile("street_top_edge_left_debris_1"); assignNameToNextTile("street_top_debris_1"); assignNameToNextTile("street_top_debris_2"); assignNameToNextTile("street_ramp_left_top"); assignNameToNextTile("street_ramp_top"); assignNameToNextTile("street_ramp_right_top"); assignNameToNextTile("street_phone_top_left"); assignNameToNextTile("street_phone_top_right"); assignNameToNextTile("street_alley_floor_start"); assignNameToNextTile("street_bottom_edge_left"); assignNameToNextTile("street_bottom_1"); assignNameToNextTile("street_bottom_ladder"); assignNameToNextTile("street_bottom_2"); assignNameToNextTile("street_bottom_edge_right"); assignNameToNextTile("street_ladder"); assignNameToNextTile("street_window_shattered"); assignNameToNextTile("street_window_broken"); assignNameToNextTile("street_ramp_left_bottom"); assignNameToNextTile("street_ramp_bottom"); assignNameToNextTile("street_ramp_right_bottom"); assignNameToNextTile("street_phone_top_front_left"); assignNameToNextTile("street_phone_top_front_right"); assignNameToNextTile("street_alley_floor_start_bottom"); assignNameToNextTile("street_wall_end_left_1"); assignNameToNextTile("street_wall_end_dirt_1"); assignNameToNextTile("street_wall_1"); assignNameToNextTile("street_wall_2"); assignNameToNextTile("street_wall_end_right_1"); assignNameToNextTile("street_window_left"); assignNameToNextTile("street_window_top"); assignNameToNextTile("street_window_right"); assignNameToNextTile("street_none+a=sda__"); assignNameToNextTile("street_wood_half_top"); assignNameToNextTile("street_wood_full_top"); assignNameToNextTile("street_phone_front_top_left"); assignNameToNextTile("street_phone_front_top_right"); assignNameToNextTile("street_floor"); assignNameToNextTile("street_wall_end_left_2"); assignNameToNextTile("street_wall_end_dirt_2"); assignNameToNextTile("street_wall_3"); assignNameToNextTile("street_wall_4"); assignNameToNextTile("street_wall_end_right_2"); assignNameToNextTile("street_window_bottom_left"); assignNameToNextTile("street_window_bottom"); assignNameToNextTile("street_window_bottom_right"); assignNameToNextTile("street_wood_bottom_1"); assignNameToNextTile("street_wood_bottom_2"); assignNameToNextTile("street_wood_bottom_3"); assignNameToNextTile("street_phone_front_bottom_left"); assignNameToNextTile("street_phone_front_bottom_right"); assignNameToNextTile("street_hydrant_top"); assignNameToNextTile("street_green_awning_top_left"); assignNameToNextTile("street_green_awning_top_middle"); assignNameToNextTile("street_green_awning_top_right"); assignNameToNextTile("street_platform_top_left"); assignNameToNextTile("street_platform_top_middle"); assignNameToNextTile("street_platform_top_right"); assignNameToNextTile("street_gate_top_left"); assignNameToNextTile("street_gate_top_middle"); assignNameToNextTile("street_gate_top_right"); assignNameToNextTile("street_fence_top_left"); assignNameToNextTile("street_fence_top_middle"); assignNameToNextTile("street_fence_top_right"); assignNameToNextTile("street_lamp_top"); assignNameToNextTile("street_hydrant_bottom"); assignNameToNextTile("street_green_awning_bottom_left"); assignNameToNextTile("street_green_awning_bottom_middle"); assignNameToNextTile("street_green_awning_bottom_right"); assignNameToNextTile("street_platform_bottom_left"); assignNameToNextTile("street_platform_bottom_middle"); assignNameToNextTile("street_platform_bottom_right"); assignNameToNextTile("street_gate_bottom_left"); assignNameToNextTile("street_gate_bottom_middle"); assignNameToNextTile("street_gate_bottom_right"); assignNameToNextTile("street_fence_bottom_left"); assignNameToNextTile("street_fence_bottom_middle"); assignNameToNextTile("street_fence_bottom_right"); assignNameToNextTile("street_lamp_off_top"); assignNameToNextTile("street_pole"); assignNameToNextTile("street_asphalt_top_left_1"); assignNameToNextTile("street_asphalt_top_right_1"); assignNameToNextTile("street_asphalt_top_left_2"); assignNameToNextTile("street_asphalt_top_right_2"); assignNameToNextTile("street_NOxcxzczxczNENEZ)Z)"); assignNameToNextTile("street_gutter"); assignNameToNextTile("street_sidewalk_1"); assignNameToNextTile("street_sidewalk_2"); assignNameToNextTile("street_sidewalk_3"); assignNameToNextTile("street_sidewalk_4"); assignNameToNextTile("street_door_top_left"); assignNameToNextTile("street_door_top_right"); assignNameToNextTile("street_lamp_body"); assignNameToNextTile("street_pole_body"); assignNameToNextTile("street_asphalt_to_pavement_1"); assignNameToNextTile("street_asphalt_to_pavement_2"); assignNameToNextTile("street_asphalt_to_pavement_3"); assignNameToNextTile("street_asphalt_to_pavement_4"); assignNameToNextTile("street_baseboard_1"); assignNameToNextTile("street_gutter_with_critter"); assignNameToNextTile("street_pavement_banana"); assignNameToNextTile("street_pavement_bottle"); assignNameToNextTile("street_pavement_debris"); assignNameToNextTile("street_pavement_apple"); assignNameToNextTile("street_door_mid_left"); assignNameToNextTile("street_door_mid_right"); assignNameToNextTile("street_lamp_body_bot"); assignNameToNextTile("street_pole_body_bot"); assignNameToNextTile("street_pavement_1"); assignNameToNextTile("street_pavement_2"); assignNameToNextTile("street_pavement_3"); assignNameToNextTile("street_pavement_4"); assignNameToNextTile("street_baseboard_2"); assignNameToNextTile("street_platform"); assignNameToNextTile("street_baseboard_3"); assignNameToNextTile("street_baseboard_4"); assignNameToNextTile("street_baseboard_5"); assignNameToNextTile("street_baseboard_6"); assignNameToNextTile("street_door_bottom_left"); assignNameToNextTile("street_door_bottom_right"); assignNameToNextTile("street_lamp_base"); assignNameToNextTile("street_pole_base"); assignNameToNextTile("street_scaffold_top_1"); assignNameToNextTile("street_scaffold_top_2"); assignNameToNextTile("street_scaffold_top_3"); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); assignNameToNextTile("street_scaffold_mid_1"); assignNameToNextTile("street_scaffold_mid_1-1"); assignNameToNextTile("street_scaffold_mid_2"); skipNextTile(); assignNameToNextTile("street_scaffold_mid_3"); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); assignNameToNextTile("street_scaffold_base_1"); assignNameToNextTile("street_scaffold_base_1-1"); assignNameToNextTile("street_scaffold_base_2"); assignNameToNextTile("street_scaffold_mid_4"); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); } public static function get instance():StreetTileset{ return (s_instance); } } }//package shared
Section 371
//TMNTButtonFactory (shared.TMNTButtonFactory) package shared { import flash.display.*; import flash.geom.*; import flash.text.*; import com.urbansquall.ui.*; import com.urbansquall.display.*; import flash.filters.*; public class TMNTButtonFactory extends VistaButtonFactory { private var m_tile9Data:Tile9Data; private var m_buttonOverlay:BitmapData; private static const DESCRIPTION_COLOR:uint = 6773846; private static const HEADER_COLOR:uint = 0xFFFFFF; private static var s_instance:TMNTButtonFactory = null; public function TMNTButtonFactory(){ m_tile9Data = new Tile9Data(new AssetLibrary.BTN_TILE9(), new Rectangle(6, 8, 12, 8)); m_buttonOverlay = new AssetLibrary.BTN_OVERLAY().bitmapData; super(HEADER_COLOR, DESCRIPTION_COLOR, 65, 42, m_tile9Data, m_buttonOverlay); } override public function createHeaderTextField():TextField{ var textfield:TextField = new DefaultTextField("", HEADER_COLOR, 26); textfield.filters = [new GlowFilter(0, 1, 1, 1, 2), new DropShadowFilter()]; textfield.selectable = false; textfield.mouseEnabled = false; return (textfield); } override public function createDescriptionTextField():TextField{ var textfield:TextField; textfield = new DefaultTextField("", DESCRIPTION_COLOR, 14); textfield.selectable = false; textfield.mouseEnabled = false; return (textfield); } public static function get instance():TMNTButtonFactory{ if (s_instance == null){ s_instance = new (TMNTButtonFactory); }; return (s_instance); } } }//package shared
Section 372
//TMNTTileLibrary (shared.TMNTTileLibrary) package shared { import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.tilemaps.*; import com.urbansquall.display.*; import com.urbansquall.prophet.physics.*; public class TMNTTileLibrary extends TileLibrary { private static const RAMP_RATIO:Number = 0.25; private static const RAMP_FRICTION:Number = 10000; public function TMNTTileLibrary(){ super(32, 32, TileLibrary.DRAW_DIRECTION_BOTTOM_TO_TOP); registerTiles(); } public function registerDecorativeTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerTiles():void{ var tileDefinition:TileDefinition; var activeTileSet:TileSet; activeTileSet = RoofTileset.instance; registerDecorativeTile("roof_top_edge_1", activeTileSet); registerDecorativeTile("roof_top_edge_2", activeTileSet); registerDecorativeTile("roof_top_edge_3", activeTileSet); registerDecorativeTile("roof_top_edge_4", activeTileSet); registerDecorativeTile("roof_top_edge_5", activeTileSet); registerDecorativeTile("roof_pizza_1", activeTileSet); registerDecorativeTile("roof_pizza_2", activeTileSet); registerDecorativeTile("roof_pizza_3", activeTileSet); registerQuarterTile("roof_top_1", activeTileSet); registerQuarterTile("roof_top_2", activeTileSet); registerQuarterTile("roof_top_exhaust", activeTileSet); registerQuarterTile("roof_top_3", activeTileSet); registerQuarterTile("roof_top_4", activeTileSet); registerQuarterTile("roof_top_edge_left", activeTileSet); registerQuarterTile("roof_top_debris_1", activeTileSet); registerQuarterTile("roof_top_debris_2", activeTileSet); registerDecorativeTile("roof_lamp_top", activeTileSet); registerBottomRightRampTile("roof_ramp_top", activeTileSet); registerQuarterTile("roof_ramp_end_left", activeTileSet); registerDecorativeTile("roof_pizza_4", activeTileSet); registerDecorativeTile("roof_pizza_5", activeTileSet); registerDecorativeTile("roof_pizza_6", activeTileSet); registerSolidTile("roof_bottom_1", activeTileSet); registerSolidTile("roof_bottom_2", activeTileSet); registerSolidTile("roof_bottom_ladder", activeTileSet); registerSolidTile("roof_bottom_3", activeTileSet); registerSolidTile("roof_bottom_4", activeTileSet); registerSolidTile("roof_ladder", activeTileSet); registerSolidTile("roof_broken_window_1", activeTileSet); registerSolidTile("roof_broker_window_2", activeTileSet); registerDecorativeTile("roof_lamp_middle", activeTileSet); registerTopLeftRampTile("roof_ramp_bottom", activeTileSet); registerQuarterTile("roof_ramp_end_right", activeTileSet); registerSolidTile("roof_wall_end_left_1", activeTileSet); registerSolidTile("roof_wall_end_dirt_1", activeTileSet); registerSolidTile("roof_wall_1", activeTileSet); registerSolidTile("roof_wall_2", activeTileSet); registerSolidTile("roof_wall_end_right_1", activeTileSet); registerDecorativeTile("roof_window_left", activeTileSet); registerSolidTile("roof_window_top", activeTileSet); registerDecorativeTile("roof_window_right", activeTileSet); registerDecorativeTile("roof_lamp_bottom", activeTileSet); registerQuarterTile("roof_wood_half_top", activeTileSet); registerQuarterTile("roof_wood_full_top", activeTileSet); registerSolidTile("roof_wall_end_left_2", activeTileSet); registerSolidTile("roof_wall_end_dirt_2", activeTileSet); registerSolidTile("roof_wall_3", activeTileSet); registerSolidTile("roof_wall_4", activeTileSet); registerSolidTile("roof_wall_end_right_2", activeTileSet); registerDecorativeTile("roof_window_bottom_left", activeTileSet); registerSolidTile("roof_window_bottom", activeTileSet); registerDecorativeTile("roof_window_bottom_right", activeTileSet); registerSolidTile("roof_wood_bottom_1", activeTileSet); registerSolidTile("roof_wood_bottom_2", activeTileSet); registerSolidTile("roof_wood_bottom_3", activeTileSet); activeTileSet = StreetTileset.instance; registerDecorativeTile("street_top_edge_1", activeTileSet); registerDecorativeTile("street_top_edge_2", activeTileSet); registerDecorativeTile("street_top_edge_3", activeTileSet); registerDecorativeTile("street_top_edge_4", activeTileSet); registerDecorativeTile("street_top_edge_5", activeTileSet); registerDecorativeTile("street_pole_1", activeTileSet); registerDecorativeTile("street_pole_2", activeTileSet); registerDecorativeTile("street_pole_3", activeTileSet); registerDecorativeTile("street_none_4", activeTileSet); registerDecorativeTile("street_none_5", activeTileSet); registerDecorativeTile("street_none_6", activeTileSet); registerDecorativeTile("street_none_7", activeTileSet); registerDecorativeTile("street_none_8", activeTileSet); registerSolidTile("street_SOLID_floor", activeTileSet); registerDecorativeTile("street_top_edge_left", activeTileSet); registerDecorativeTile("street_top_1", activeTileSet); registerDecorativeTile("street_top_exhaust", activeTileSet); registerDecorativeTile("street_top_2", activeTileSet); registerDecorativeTile("street_top_edge_right", activeTileSet); registerDecorativeTile("street_top_edge_left_debris_1", activeTileSet); registerDecorativeTile("street_top_debris_1", activeTileSet); registerDecorativeTile("street_top_debris_2", activeTileSet); registerDecorativeTile("street_ramp_left_top", activeTileSet); registerDecorativeTile("street_ramp_top", activeTileSet); registerDecorativeTile("street_ramp_right_top", activeTileSet); registerQuarterTile("street_phone_top_left", activeTileSet); registerQuarterTile("street_phone_top_right", activeTileSet); registerDecorativeTile("street_alley_floor_start", activeTileSet); registerDecorativeTile("street_bottom_edge_left", activeTileSet); registerDecorativeTile("street_bottom_1", activeTileSet); registerDecorativeTile("street_bottom_ladder", activeTileSet); registerDecorativeTile("street_bottom_2", activeTileSet); registerDecorativeTile("street_bottom_edge_right", activeTileSet); registerDecorativeTile("street_ladder", activeTileSet); registerDecorativeTile("street_window_shattered", activeTileSet); registerDecorativeTile("street_window_broken", activeTileSet); registerDecorativeTile("street_ramp_left_bottom", activeTileSet); registerDecorativeTile("street_ramp_bottom", activeTileSet); registerDecorativeTile("street_ramp_right_bottom", activeTileSet); registerSolidTile("street_phone_top_front_left", activeTileSet); registerSolidTile("street_phone_top_front_right", activeTileSet); registerDecorativeTile("street_alley_floor_start_bottom", activeTileSet); registerDecorativeTile("street_wall_end_left_1", activeTileSet); registerDecorativeTile("street_wall_end_dirt_1", activeTileSet); registerDecorativeTile("street_wall_1", activeTileSet); registerDecorativeTile("street_wall_2", activeTileSet); registerDecorativeTile("street_wall_end_right_1", activeTileSet); registerDecorativeTile("street_window_left", activeTileSet); registerDecorativeTile("street_window_top", activeTileSet); registerDecorativeTile("street_window_right", activeTileSet); registerDecorativeTile("street_wood_half_top", activeTileSet); registerQuarterTile("street_wood_full_top", activeTileSet); registerSolidTile("street_phone_front_top_left", activeTileSet); registerSolidTile("street_phone_front_top_right", activeTileSet); registerQuarterTile("street_floor", activeTileSet); registerDecorativeTile("street_wall_end_left_2", activeTileSet); registerDecorativeTile("street_wall_end_dirt_2", activeTileSet); registerDecorativeTile("street_wall_3", activeTileSet); registerDecorativeTile("street_wall_4", activeTileSet); registerDecorativeTile("street_wall_end_right_2", activeTileSet); registerDecorativeTile("street_window_bottom_left", activeTileSet); registerDecorativeTile("street_window_bottom", activeTileSet); registerDecorativeTile("street_window_bottom_right", activeTileSet); registerSolidTile("street_wood_bottom_1", activeTileSet); registerSolidTile("street_wood_bottom_2", activeTileSet); registerSolidTile("street_wood_bottom_3", activeTileSet); registerSolidTile("street_phone_front_bottom_left", activeTileSet); registerSolidTile("street_phone_front_bottom_right", activeTileSet); registerDecorativeTile("street_hydrant_top", activeTileSet); registerDecorativeTile("street_green_awning_top_left", activeTileSet); registerDecorativeTile("street_green_awning_top_middle", activeTileSet); registerDecorativeTile("street_green_awning_top_right", activeTileSet); registerDecorativeTile("street_platform_top_left", activeTileSet); registerDecorativeTile("street_platform_top_middle", activeTileSet); registerDecorativeTile("street_platform_top_right", activeTileSet); registerDecorativeTile("street_gate_top_left", activeTileSet); registerDecorativeTile("street_gate_top_middle", activeTileSet); registerDecorativeTile("street_gate_top_right", activeTileSet); registerDecorativeTile("street_fence_top_left", activeTileSet); registerDecorativeTile("street_fence_top_middle", activeTileSet); registerDecorativeTile("street_fence_top_right", activeTileSet); registerDecorativeTile("street_lamp_top", activeTileSet); registerDecorativeTile("street_hydrant_bottom", activeTileSet); registerSolidTile("street_green_awning_bottom_left", activeTileSet); registerSolidTile("street_green_awning_bottom_middle", activeTileSet); registerSolidTile("street_green_awning_bottom_right", activeTileSet); registerSolidTile("street_platform_bottom_left", activeTileSet); registerSolidTile("street_platform_bottom_middle", activeTileSet); registerSolidTile("street_platform_bottom_right", activeTileSet); registerDecorativeTile("street_gate_bottom_left", activeTileSet); registerDecorativeTile("street_gate_bottom_middle", activeTileSet); registerDecorativeTile("street_gate_bottom_right", activeTileSet); registerDecorativeTile("street_fence_bottom_left", activeTileSet); registerDecorativeTile("street_fence_bottom_middle", activeTileSet); registerDecorativeTile("street_fence_bottom_right", activeTileSet); registerDecorativeTile("street_lamp_off_top", activeTileSet); registerDecorativeTile("street_pole", activeTileSet); registerDecorativeTile("street_asphalt_top_left_1", activeTileSet); registerDecorativeTile("street_asphalt_top_right_1", activeTileSet); registerDecorativeTile("street_asphalt_top_left_2", activeTileSet); registerDecorativeTile("street_asphalt_top_right_2", activeTileSet); registerDecorativeTile("street_NOxcxzczxczNENEZ)Z)", activeTileSet); registerSolidTile("street_gutter", activeTileSet); registerSolidTile("street_sidewalk_1", activeTileSet); registerSolidTile("street_sidewalk_2", activeTileSet); registerSolidTile("street_sidewalk_3", activeTileSet); registerSolidTile("street_sidewalk_4", activeTileSet); registerDecorativeTile("street_door_top_left", activeTileSet); registerDecorativeTile("street_door_top_right", activeTileSet); registerDecorativeTile("street_lamp_body", activeTileSet); registerDecorativeTile("street_pole_body", activeTileSet); registerDecorativeTile("street_asphalt_to_pavement_1", activeTileSet); registerDecorativeTile("street_asphalt_to_pavement_2", activeTileSet); registerDecorativeTile("street_asphalt_to_pavement_3", activeTileSet); registerDecorativeTile("street_asphalt_to_pavement_4", activeTileSet); registerDecorativeTile("street_baseboard_1", activeTileSet); registerSolidTile("street_gutter_with_critter", activeTileSet); registerSolidTile("street_pavement_banana", activeTileSet); registerSolidTile("street_pavement_bottle", activeTileSet); registerSolidTile("street_pavement_debris", activeTileSet); registerSolidTile("street_pavement_apple", activeTileSet); registerDecorativeTile("street_door_mid_left", activeTileSet); registerDecorativeTile("street_door_mid_right", activeTileSet); registerDecorativeTile("street_lamp_body_bot", activeTileSet); registerDecorativeTile("street_pole_body_bot", activeTileSet); registerQuarterTile("street_pavement_1", activeTileSet); registerQuarterTile("street_pavement_2", activeTileSet); registerQuarterTile("street_pavement_3", activeTileSet); registerQuarterTile("street_pavement_4", activeTileSet); registerSolidTile("street_baseboard_2", activeTileSet); registerDecorativeTile("street_platform", activeTileSet); registerDecorativeTile("street_baseboard_3", activeTileSet); registerDecorativeTile("street_baseboard_4", activeTileSet); registerDecorativeTile("street_baseboard_5", activeTileSet); registerDecorativeTile("street_baseboard_6", activeTileSet); registerDecorativeTile("street_door_bottom_left", activeTileSet); registerDecorativeTile("street_door_bottom_right", activeTileSet); registerDecorativeTile("street_lamp_base", activeTileSet); registerDecorativeTile("street_pole_base", activeTileSet); registerQuarterTile("street_scaffold_top_1", activeTileSet); registerQuarterTile("street_scaffold_top_2", activeTileSet); registerQuarterTile("street_scaffold_top_3", activeTileSet); registerSolidTile("street_scaffold_mid_1", activeTileSet); registerSolidTile("street_scaffold_mid_1-1", activeTileSet); registerSolidTile("street_scaffold_mid_2", activeTileSet); registerSolidTile("street_scaffold_mid_3", activeTileSet); registerSolidTile("street_scaffold_base_1", activeTileSet); registerSolidTile("street_scaffold_base_1-1", activeTileSet); registerSolidTile("street_scaffold_base_2", activeTileSet); registerSolidTile("street_scaffold_mid_4", activeTileSet); activeTileSet = WarehouseTileset.instance; registerDecorativeTile("wh_bg_1", activeTileSet); registerDecorativeTile("wh_bg_2", activeTileSet); registerDecorativeTile("wh_bg_3", activeTileSet); registerDecorativeTile("wh_bg_4", activeTileSet); registerDecorativeTile("wh_bg_5", activeTileSet); registerDecorativeTile("wh_bg_6", activeTileSet); registerDecorativeTile("wh_bg_7", activeTileSet); registerDecorativeTile("wh_bg_8", activeTileSet); registerDecorativeTile("wh_bg_9", activeTileSet); registerDecorativeTile("wh_bg_10", activeTileSet); registerDecorativeTile("wh_bg_11", activeTileSet); registerDecorativeTile("wh_bg_12", activeTileSet); registerDecorativeTile("wh_floor_1", activeTileSet); registerDecorativeTile("wh_floor_2", activeTileSet); registerDecorativeTile("wh_box_top_left", activeTileSet); registerDecorativeTile("wh_box_top_middle", activeTileSet); registerDecorativeTile("wh_box_top_right", activeTileSet); registerSolidTile("wh_box_1", activeTileSet); registerSolidTile("wh_box_2", activeTileSet); registerDecorativeTile("wh_shelf_top_left", activeTileSet); registerDecorativeTile("wh_shelf_top_middle_1", activeTileSet); registerDecorativeTile("wh_shelf_top_middle_2", activeTileSet); registerDecorativeTile("wh_shelf_top_right", activeTileSet); registerQuarterTile("wh_crate_top", activeTileSet); registerDecorativeTile("wh_window_grate", activeTileSet); registerTopLeftRampTile("wh_ramp_left_wired", activeTileSet); registerQuarterTile("wh_floor_3", activeTileSet); registerQuarterTile("wh_floor_4", activeTileSet); registerQuarterTile("wh_box_top_middle_left", activeTileSet); registerQuarterTile("wh_box_top_middle_middle", activeTileSet); registerQuarterTile("wh_box_top_middle_right", activeTileSet); registerSolidTile("wh_box_3", activeTileSet); registerSolidTile("wh_box_4", activeTileSet); registerQuarterTile("wh_shelf_front_left", activeTileSet); registerQuarterTile("wh_shelf_front_middle_1", activeTileSet); registerQuarterTile("wh_shelf_front_middle_2", activeTileSet); registerQuarterTile("wh_shelf_front_right", activeTileSet); registerSolidTile("wh_crate_front", activeTileSet); registerDecorativeTile("wh_window_grate_bottom", activeTileSet); registerTopRightRampTile("wh_ramp_right_wired", activeTileSet); registerDecorativeTile("wh_floor_5", activeTileSet); registerDecorativeTile("wh_floor_6", activeTileSet); registerSolidTile("wh_box_front_top_left", activeTileSet); registerSolidTile("wh_box_front_top_middle", activeTileSet); registerSolidTile("wh_box_front_top_right", activeTileSet); registerSolidTile("wh_box_5", activeTileSet); registerSolidTile("wh_box_6", activeTileSet); registerSolidTile("wh_shelf_middle_left_1", activeTileSet); registerSolidTile("wh_shelf_middle_1", activeTileSet); registerSolidTile("wh_shelf_middle_2", activeTileSet); registerSolidTile("wh_shelf_middle_right_1", activeTileSet); registerBottomLeftRampTile("wh_ramp_left", activeTileSet); registerBottomRightRampTile("wh_ramp_right", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONE", activeTileSet); registerQuarterTile("wh_floor_7", activeTileSet); registerQuarterTile("wh_floor_8", activeTileSet); registerSolidTile("wh_box_front_middle_left", activeTileSet); registerDecorativeTile("wh_box_front_middle_middle", activeTileSet); registerSolidTile("wh_box_front_middle_right", activeTileSet); registerSolidTile("wh_box_7", activeTileSet); registerSolidTile("wh_box_8", activeTileSet); registerSolidTile("wh_shelf_middle_left_2", activeTileSet); registerSolidTile("wh_shelf_middle_3", activeTileSet); registerSolidTile("wh_shelf_middle_4", activeTileSet); registerSolidTile("wh_shelf_middle_right_2", activeTileSet); registerTopRightRampTile("wh_ramp_bottom_left", activeTileSet); registerTopLeftRampTile("wh_ramp_bottom_right", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasda", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasdaasdd", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasdafffsadf", activeTileSet); registerSolidTile("wh_box_front_bottom_left", activeTileSet); registerSolidTile("wh_box_front_bottom_middle", activeTileSet); registerSolidTile("wh_box_front_bottom_right", activeTileSet); registerSolidTile("wh_box_9", activeTileSet); registerSolidTile("wh_box_10", activeTileSet); registerSolidTile("wh_shelf_middle_left_3", activeTileSet); registerSolidTile("wh_shelf_middle_5", activeTileSet); registerSolidTile("wh_shelf_middle_6", activeTileSet); registerSolidTile("wh_shelf_middle_right_3", activeTileSet); registerQuarterTile("wh_ramp_flat", activeTileSet); registerDecorativeTile("wh_ramp_wires", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasdaaa", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasdaasdd234", activeTileSet); registerDecorativeTile("wh_BLANKBLANKNONEasdafffsadf4", activeTileSet); registerDecorativeTile("wh_acid_top_left", activeTileSet); registerDecorativeTile("wh_acid_top_mid", activeTileSet); registerDecorativeTile("wh_acid_top_right", activeTileSet); registerSolidTile("wh_boxd_1", activeTileSet); registerSolidTile("wh_boxd_2", activeTileSet); registerSolidTile("wh_boxd_3", activeTileSet); registerSolidTile("wh_boxd_4", activeTileSet); registerSolidTile("wh_boxd_5", activeTileSet); registerSolidTile("wh_boxd_6", activeTileSet); registerSolidTile("wh_boxd_7", activeTileSet); registerSolidTile("wh_boxd_8", activeTileSet); registerSolidTile("wh_boxd_9", activeTileSet); tileDefinition = registerQuarterTile("wh_acid_bottom_left", activeTileSet); tileDefinition.properties.setBoolean("acidic", true); tileDefinition = registerQuarterTile("wh_acid_bottom_mid", activeTileSet); tileDefinition.properties.setBoolean("acidic", true); tileDefinition = registerQuarterTile("wh_acid_bottom_right", activeTileSet); tileDefinition.properties.setBoolean("acidic", true); registerSolidTile("wh_boxd_10", activeTileSet); registerSolidTile("wh_boxd_11", activeTileSet); registerSolidTile("wh_boxd_12", activeTileSet); registerSolidTile("wh_boxd_13", activeTileSet); tileDefinition = new TileDefinition(); tileDefinition.name = "roof_wall"; tileDefinition.setName = "uglies"; tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = 0.5; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices = TileShapeHelper.createRectangle(tileWidth, tileHeight); tileDefinition.simpleBitmapData = new AssetLibrary.ROOF_WALL().bitmapData; registerTileDefinition(tileDefinition); tileDefinition = new TileDefinition(); tileDefinition.name = "roof_wall_slick"; tileDefinition.setName = "uglies"; tileDefinition.vertices = TileShapeHelper.createRectangle(tileWidth, tileHeight); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = 0; tileDefinition.polyDef.restitution = 0; tileDefinition.properties.setBoolean("grabbable", false); tileDefinition.simpleBitmapData = new AssetLibrary.ROOF_WALL_SLICK().bitmapData; registerTileDefinition(tileDefinition); } public function registerBottomLeftRampTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = RAMP_FRICTION; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices.push(0); tileDefinition.vertices.push((tileHeight - (RAMP_RATIO * tileHeight))); tileDefinition.vertices.push((RAMP_RATIO * tileWidth)); tileDefinition.vertices.push(tileHeight); tileDefinition.vertices.push(0); tileDefinition.vertices.push(tileHeight); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerSolidTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = 0; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices = TileShapeHelper.createRectangle(tileWidth, tileHeight); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerQuarterTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = 0.5; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices = TileShapeHelper.createRectangle(tileWidth, (tileHeight / 4), 0, ((tileHeight * 3) / 4)); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerTopLeftRampTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = RAMP_FRICTION; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices.push((tileWidth - (RAMP_RATIO * tileWidth))); tileDefinition.vertices.push(0); tileDefinition.vertices.push(tileWidth); tileDefinition.vertices.push(0); tileDefinition.vertices.push(0); tileDefinition.vertices.push(tileHeight); tileDefinition.vertices.push(0); tileDefinition.vertices.push((tileHeight - (RAMP_RATIO * tileHeight))); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerTopRightRampTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = RAMP_FRICTION; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices.push(0); tileDefinition.vertices.push(0); tileDefinition.vertices.push((RAMP_RATIO * tileWidth)); tileDefinition.vertices.push(0); tileDefinition.vertices.push(tileWidth); tileDefinition.vertices.push((tileHeight - (RAMP_RATIO * tileHeight))); tileDefinition.vertices.push(tileWidth); tileDefinition.vertices.push(tileHeight); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } public function registerBottomRightRampTile(a_name:String, a_tileSet:TileSet):TileDefinition{ var tileDefinition:TileDefinition; tileDefinition = new TileDefinition(); tileDefinition.polyDef = new PolygonDef(); tileDefinition.polyDef.friction = RAMP_FRICTION; tileDefinition.polyDef.restitution = 0; tileDefinition.vertices.push(tileWidth); tileDefinition.vertices.push((tileHeight - (RAMP_RATIO * tileHeight))); tileDefinition.vertices.push(tileWidth); tileDefinition.vertices.push(tileHeight); tileDefinition.vertices.push((tileWidth - (RAMP_RATIO * tileWidth))); tileDefinition.vertices.push(tileHeight); tileDefinition.name = a_name; tileDefinition.setName = a_tileSet.setName; tileDefinition.simpleBitmapData = a_tileSet.lookupTileBitmapData(a_name); registerTileDefinition(tileDefinition); return (tileDefinition); } } }//package shared
Section 373
//TMNTToolTip (shared.TMNTToolTip) package shared { import flash.display.*; import com.urbansquall.ui.*; public class TMNTToolTip { public function TMNTToolTip(){ super(); } public static function attachToolTip(a_target:DisplayObject, a_description:String):void{ var container:Sprite = new Sprite(); var descriptionTF:DefaultTextField = new DefaultTextField(); descriptionTF.mouseEnabled = false; descriptionTF.autoSize = "left"; descriptionTF.text = ((" " + a_description) + " "); descriptionTF.background = true; descriptionTF.backgroundColor = 0xFFFFFF; descriptionTF.border = true; descriptionTF.borderColor = 0; descriptionTF.textColor = 0; container.addChild(descriptionTF); ToolTip.attachToolTip(a_target, container); } } }//package shared
Section 374
//WarehouseTileset (shared.WarehouseTileset) package shared { import flash.display.*; import com.urbansquall.display.*; public class WarehouseTileset extends TileSet { private static var s_instance:WarehouseTileset; public function WarehouseTileset(){ s_instance = this; var bitmapData:BitmapData = (new AssetLibrary.WAREHOUSE_TILESET() as Bitmap).bitmapData; super("wh", 32, 32, bitmapData); assignNameToNextTile("wh_bg_1"); assignNameToNextTile("wh_bg_2"); assignNameToNextTile("wh_bg_3"); assignNameToNextTile("wh_bg_4"); assignNameToNextTile("wh_bg_5"); assignNameToNextTile("wh_bg_6"); assignNameToNextTile("wh_bg_7"); assignNameToNextTile("wh_bg_8"); assignNameToNextTile("wh_bg_9"); assignNameToNextTile("wh_bg_10"); assignNameToNextTile("wh_bg_11"); assignNameToNextTile("wh_bg_12"); assignNameToNextTile("wh_floor_1"); assignNameToNextTile("wh_floor_2"); assignNameToNextTile("wh_box_top_left"); assignNameToNextTile("wh_box_top_middle"); assignNameToNextTile("wh_box_top_right"); assignNameToNextTile("wh_box_1"); assignNameToNextTile("wh_box_2"); assignNameToNextTile("wh_shelf_top_left"); assignNameToNextTile("wh_shelf_top_middle_1"); assignNameToNextTile("wh_shelf_top_middle_2"); assignNameToNextTile("wh_shelf_top_right"); assignNameToNextTile("wh_crate_top"); assignNameToNextTile("wh_window_grate"); assignNameToNextTile("wh_ramp_left_wired"); assignNameToNextTile("wh_floor_3"); assignNameToNextTile("wh_floor_4"); assignNameToNextTile("wh_box_top_middle_left"); assignNameToNextTile("wh_box_top_middle_middle"); assignNameToNextTile("wh_box_top_middle_right"); assignNameToNextTile("wh_box_3"); assignNameToNextTile("wh_box_4"); assignNameToNextTile("wh_shelf_front_left"); assignNameToNextTile("wh_shelf_front_middle_1"); assignNameToNextTile("wh_shelf_front_middle_2"); assignNameToNextTile("wh_shelf_front_right"); assignNameToNextTile("wh_crate_front"); assignNameToNextTile("wh_window_grate_bottom"); assignNameToNextTile("wh_ramp_right_wired"); assignNameToNextTile("wh_floor_5"); assignNameToNextTile("wh_floor_6"); assignNameToNextTile("wh_box_front_top_left"); assignNameToNextTile("wh_box_front_top_middle"); assignNameToNextTile("wh_box_front_top_right"); assignNameToNextTile("wh_box_5"); assignNameToNextTile("wh_box_6"); assignNameToNextTile("wh_shelf_middle_left_1"); assignNameToNextTile("wh_shelf_middle_1"); assignNameToNextTile("wh_shelf_middle_2"); assignNameToNextTile("wh_shelf_middle_right_1"); assignNameToNextTile("wh_ramp_right"); assignNameToNextTile("wh_ramp_left"); assignNameToNextTile("wh_BLANKBLANKNONE"); assignNameToNextTile("wh_floor_7"); assignNameToNextTile("wh_floor_8"); assignNameToNextTile("wh_box_front_middle_left"); assignNameToNextTile("wh_box_front_middle_middle"); assignNameToNextTile("wh_box_front_middle_right"); assignNameToNextTile("wh_box_7"); assignNameToNextTile("wh_box_8"); assignNameToNextTile("wh_shelf_middle_left_2"); assignNameToNextTile("wh_shelf_middle_3"); assignNameToNextTile("wh_shelf_middle_4"); assignNameToNextTile("wh_shelf_middle_right_2"); assignNameToNextTile("wh_ramp_bottom_right"); assignNameToNextTile("wh_ramp_bottom_left"); assignNameToNextTile("wh_BLANKBLANKNONEasda"); assignNameToNextTile("wh_BLANKBLANKNONEasdaasdd"); assignNameToNextTile("wh_BLANKBLANKNONEasdafffsadf"); assignNameToNextTile("wh_box_front_bottom_left"); assignNameToNextTile("wh_box_front_bottom_middle"); assignNameToNextTile("wh_box_front_bottom_right"); assignNameToNextTile("wh_box_9"); assignNameToNextTile("wh_box_10"); assignNameToNextTile("wh_shelf_middle_left_3"); assignNameToNextTile("wh_shelf_middle_5"); assignNameToNextTile("wh_shelf_middle_6"); assignNameToNextTile("wh_shelf_middle_right_3"); assignNameToNextTile("wh_ramp_flat"); assignNameToNextTile("wh_ramp_wires"); assignNameToNextTile("wh_BLANKBLANKNONEasdaaa"); assignNameToNextTile("wh_BLANKBLANKNONEasdaasdd234"); assignNameToNextTile("wh_BLANKBLANKNONEasdafffsadf4"); assignNameToNextTile("wh_acid_top_left"); assignNameToNextTile("wh_acid_top_mid"); assignNameToNextTile("wh_acid_top_right"); skipNextTile(); skipNextTile(); assignNameToNextTile("wh_boxd_1"); assignNameToNextTile("wh_boxd_2"); assignNameToNextTile("wh_boxd_3"); assignNameToNextTile("wh_boxd_4"); assignNameToNextTile("wh_boxd_5"); assignNameToNextTile("wh_boxd_6"); assignNameToNextTile("wh_boxd_7"); assignNameToNextTile("wh_boxd_8"); assignNameToNextTile("wh_boxd_9"); assignNameToNextTile("wh_acid_bottom_left"); assignNameToNextTile("wh_acid_bottom_mid"); assignNameToNextTile("wh_acid_bottom_right"); skipNextTile(); skipNextTile(); assignNameToNextTile("wh_boxd_10"); assignNameToNextTile("wh_boxd_11"); assignNameToNextTile("wh_boxd_12"); assignNameToNextTile("wh_boxd_13"); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); skipNextTile(); } public static function get instance():WarehouseTileset{ return (s_instance); } } }//package shared
Section 375
//p01_64 (tmnt_comic_panels_cs3_fla.p01_64) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p01_64 extends MovieClip { public function p01_64(){ addFrameScript(34, frame35); } function frame35(){ } } }//package tmnt_comic_panels_cs3_fla
Section 376
//p01_67 (tmnt_comic_panels_cs3_fla.p01_67) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p01_67 extends MovieClip { public var parentObj:MovieClip; public function p01_67(){ addFrameScript(0, frame1, 29, frame30); } function frame1(){ trace("start speech"); if (this.parent.parent != null){ parentObj = (this.parent as MovieClip); trace(parentObj.currentFrame); if (parentObj.currentFrame > 80){ trace("hack: go to end"); gotoAndStop(30); }; }; } function frame30(){ stop(); trace("stop speech"); } } }//package tmnt_comic_panels_cs3_fla
Section 377
//p02_32 (tmnt_comic_panels_cs3_fla.p02_32) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_32 extends MovieClip { public function p02_32(){ addFrameScript(109, frame110); } function frame110(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 378
//p02_34 (tmnt_comic_panels_cs3_fla.p02_34) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_34 extends MovieClip { public function p02_34(){ addFrameScript(29, frame30); } function frame30(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 379
//p02_35 (tmnt_comic_panels_cs3_fla.p02_35) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_35 extends MovieClip { public function p02_35(){ addFrameScript(23, frame24); } function frame24(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 380
//p02_42 (tmnt_comic_panels_cs3_fla.p02_42) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_42 extends MovieClip { public function p02_42(){ addFrameScript(79, frame80); } function frame80(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 381
//p02_48 (tmnt_comic_panels_cs3_fla.p02_48) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_48 extends MovieClip { public function p02_48(){ addFrameScript(14, frame15); } function frame15(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 382
//p02_49 (tmnt_comic_panels_cs3_fla.p02_49) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_49 extends MovieClip { public function p02_49(){ addFrameScript(34, frame35); } function frame35(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 383
//p02_50 (tmnt_comic_panels_cs3_fla.p02_50) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p02_50 extends MovieClip { public function p02_50(){ addFrameScript(74, frame75); } function frame75(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 384
//p04_01_mc_18 (tmnt_comic_panels_cs3_fla.p04_01_mc_18) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p04_01_mc_18 extends MovieClip { public function p04_01_mc_18(){ addFrameScript(78, frame79); } function frame79(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 385
//p04_21 (tmnt_comic_panels_cs3_fla.p04_21) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p04_21 extends MovieClip { public function p04_21(){ addFrameScript(79, frame80); } function frame80(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 386
//p04_25 (tmnt_comic_panels_cs3_fla.p04_25) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p04_25 extends MovieClip { public function p04_25(){ addFrameScript(59, frame60); } function frame60(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 387
//p04_27 (tmnt_comic_panels_cs3_fla.p04_27) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p04_27 extends MovieClip { public function p04_27(){ addFrameScript(59, frame60); } function frame60(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 388
//p04_28 (tmnt_comic_panels_cs3_fla.p04_28) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p04_28 extends MovieClip { public function p04_28(){ addFrameScript(59, frame60); } function frame60(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 389
//p05_13 (tmnt_comic_panels_cs3_fla.p05_13) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p05_13 extends MovieClip { public function p05_13(){ addFrameScript(79, frame80); } function frame80(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 390
//p05_2 (tmnt_comic_panels_cs3_fla.p05_2) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p05_2 extends MovieClip { public function p05_2(){ addFrameScript(54, frame55); } function frame55(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 391
//p05_7 (tmnt_comic_panels_cs3_fla.p05_7) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class p05_7 extends MovieClip { public function p05_7(){ addFrameScript(59, frame60); } function frame60(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 392
//page01_panel01_60 (tmnt_comic_panels_cs3_fla.page01_panel01_60) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class page01_panel01_60 extends MovieClip { public function page01_panel01_60(){ addFrameScript(79, frame80); } function frame80(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 393
//page01_panel02_61 (tmnt_comic_panels_cs3_fla.page01_panel02_61) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class page01_panel02_61 extends MovieClip { public function page01_panel02_61(){ addFrameScript(89, frame90); } function frame90(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 394
//page01_panel03_71 (tmnt_comic_panels_cs3_fla.page01_panel03_71) package tmnt_comic_panels_cs3_fla { import flash.display.*; public dynamic class page01_panel03_71 extends MovieClip { public function page01_panel03_71(){ addFrameScript(79, frame80); } function frame80(){ stop(); } } }//package tmnt_comic_panels_cs3_fla
Section 395
//BladeSwipeNoise1 (BladeSwipeNoise1) package { import flash.media.*; public dynamic class BladeSwipeNoise1 extends Sound { } }//package
Section 396
//BluntSwingNoise1 (BluntSwingNoise1) package { import flash.media.*; public dynamic class BluntSwingNoise1 extends Sound { } }//package
Section 397
//BreakableWall (BreakableWall) package { import flash.media.*; public dynamic class BreakableWall extends Sound { } }//package
Section 398
//Buzz (Buzz) package { import flash.media.*; public dynamic class Buzz extends Sound { } }//package
Section 399
//DrillBox (DrillBox) package { import flash.media.*; public dynamic class DrillBox extends Sound { } }//package
Section 400
//FootSoldierDie (FootSoldierDie) package { import flash.media.*; public dynamic class FootSoldierDie extends Sound { } }//package
Section 401
//FootSoldierDie2 (FootSoldierDie2) package { import flash.media.*; public dynamic class FootSoldierDie2 extends Sound { } }//package
Section 402
//FootSoldierHit (FootSoldierHit) package { import flash.media.*; public dynamic class FootSoldierHit extends Sound { } }//package
Section 403
//FootSoldierHit2 (FootSoldierHit2) package { import flash.media.*; public dynamic class FootSoldierHit2 extends Sound { } }//package
Section 404
//FootSoldierHit3 (FootSoldierHit3) package { import flash.media.*; public dynamic class FootSoldierHit3 extends Sound { } }//package
Section 405
//GainingOozeNoise2 (GainingOozeNoise2) package { import flash.media.*; public dynamic class GainingOozeNoise2 extends Sound { } }//package
Section 406
//HitNoiseForRobots1 (HitNoiseForRobots1) package { import flash.media.*; public dynamic class HitNoiseForRobots1 extends Sound { } }//package
Section 407
//HunDie (HunDie) package { import flash.media.*; public dynamic class HunDie extends Sound { } }//package
Section 408
//HunHitWall (HunHitWall) package { import flash.media.*; public dynamic class HunHitWall extends Sound { } }//package
Section 409
//HunHuff (HunHuff) package { import flash.media.*; public dynamic class HunHuff extends Sound { } }//package
Section 410
//HunStep (HunStep) package { import flash.media.*; public dynamic class HunStep extends Sound { } }//package
Section 411
//JumpingNinjaJump (JumpingNinjaJump) package { import flash.media.*; public dynamic class JumpingNinjaJump extends Sound { } }//package
Section 412
//MachineDie1 (MachineDie1) package { import flash.media.*; public dynamic class MachineDie1 extends Sound { } }//package
Section 413
//Main (Main) package { import flash.events.*; import com.urbansquall.ginger.*; import flash.display.*; import shared.*; import flash.geom.*; import com.urbansquall.prophet.display.*; import com.urbansquall.prophet.engine.*; import com.urbansquall.ui.*; import com.urbansquall.prophet.definitions.*; import com.urbansquall.prophet.physics.*; import game.*; import game.ui.*; import Box2D.Dynamics.*; public class Main extends Sprite { public function Main():void{ super(); if (stage){ init(); } else { addEventListener(Event.ADDED_TO_STAGE, init); }; } private function init(e:Event=null):void{ removeEventListener(Event.ADDED_TO_STAGE, init); if (!(Constants.EXTERNAL_STATUS & Constants.EXTERNAL_DISABLE_TRACKING)){ trace("TRACKING ENABLED"); if (Constants.LITE_VERSION){ MochiBot.track(this, "8dcd0205"); } else { MochiBot.track(this, "94611b83"); }; }; SoundCache.init(); this.stage.stageFocusRect = false; new SafeSol("tmnt-v13", 12630659); SafeSol.instance.createBool("hide_input", false); SafeSol.instance.createInt("maxLevel", 0, true); ToolTip.initialize(this.stage); registerGingers(); createTilesets(); if (!Constants.ALLOW_DEBUG){ addChild(new Splash()); } else { addChild(new Title()); }; var muteButton:MuteButton = new MuteButton(); muteButton.name = "muteButton"; muteButton.x = (Constants.RENDER_WIDTH - 20); muteButton.y = (Constants.RENDER_HEIGHT - 20); stage.addChild(muteButton); } private function createTilesets():void{ new RoofTileset(); new StreetTileset(); new WarehouseTileset(); } private function processTurtleGinger(a_data:BitmapData):AnimationPlayer{ var y:int; var anim:Animation; var player:AnimationPlayer = new AnimationPlayer(); var fps = 20; var fastFps = 45; var graceFps = 16; var transitionFps = 90; var sz = 128; y = 0; anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 1, 0, y); player.addAnimation("idle", anim); anim = AnimationBuilder.importStrip(transitionFps, a_data, sz, sz, 1, sz, y); player.addAnimation("crouchtransition", anim); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 1, (sz * 2), y); anim.isLooping = true; player.addAnimation("crouch", anim); anim = AnimationBuilder.importStrip(fastFps, a_data, sz, sz, 4, (sz * 3), y); anim.changeFrameID(1, "attackStart"); anim.changeFrameID(2, "attackNext"); player.addAnimation("crouchattack", anim); anim = AnimationBuilder.importStrip(4, a_data, sz, sz, 1, (sz * 7), y); player.addAnimation("special", anim); y = sz; anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 6, 0, y); anim.isLooping = true; player.addAnimation("walk", anim); anim.changeFrameID(1, "step"); anim = AnimationBuilder.importStrip(4, a_data, sz, sz, 1, (sz * 6), y); player.addAnimation("groundflinch", anim); anim = AnimationBuilder.importStrip(4, a_data, sz, sz, 1, (sz * 7), y); player.addAnimation("airflinch", anim); y = (sz * 2); anim = AnimationBuilder.importStrip(fastFps, a_data, sz, sz, 4, 0, y); anim.changeFrameID(2, "attackStart"); player.addAnimation("combo1", anim); anim = AnimationBuilder.importStrip(graceFps, a_data, sz, sz, 1, (sz * 3), y); player.addAnimation("combo1Grace", anim); anim = AnimationBuilder.importStrip(fastFps, a_data, sz, sz, 4, (sz * 4), y); anim.changeFrameID(1, "attackStart"); player.addAnimation("combo2", anim); y = (sz * 3); anim = AnimationBuilder.importStrip(graceFps, a_data, sz, sz, 1, 0, y); player.addAnimation("combo2Grace", anim); anim = AnimationBuilder.importStrip(fastFps, a_data, sz, sz, 8, 0, y); anim.changeFrameID(5, "attackStart"); player.addAnimation("combo3", anim); y = (sz * 4); anim = AnimationBuilder.importStrip(transitionFps, a_data, sz, sz, 1, 0, y); player.addAnimation("jumpingtransition", anim); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 1, sz, y); player.addAnimation("jumping", anim); anim = AnimationBuilder.importStrip((fastFps + 10), a_data, sz, sz, 4, (sz * 2), y); anim.isLooping = true; player.addAnimation("falling", anim); anim = AnimationBuilder.importStrip((fastFps + 10), a_data, sz, sz, 4, (sz * 2), y); player.addAnimation("crouchattackDelay", anim); y = (sz * 5); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 4, 0, y); anim.changeFrameID(1, "attackStart"); player.addAnimation("airattack", anim); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 4, (sz * 4), y); anim.isLooping = true; player.addAnimation("wallslide", anim); y = (sz * 6); anim = AnimationBuilder.importStrip(40, a_data, sz, sz, 6, 0, y); player.addAnimation("shellrotate", anim); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 1, (sz * 6), y, 1, 0, -36); anim.changeFrameID(0, "attackStart"); anim.isLooping = true; player.addAnimation("shellattack", anim); anim = AnimationBuilder.importStrip(fastFps, a_data, sz, sz, 1, (sz * 7), y); player.addAnimation("shellexit", anim); y = (sz * 7); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 4, 0, y); player.addAnimation("deathtransition", anim); anim = AnimationBuilder.importStrip(fps, a_data, sz, sz, 4, (sz * 4), y); player.addAnimation("death", anim); return (player); } private function registerGingers():void{ var animation:Animation; var player:AnimationPlayer; var frameLocation:Rectangle; var i:int; var bitmapData:BitmapData; var gingerFactory:GingerFactory = GingerFactory.getInstance(); var fps = 20; var desiredRotations = 64; var sz = 128; var fastFps = 32; player = processTurtleGinger(new AssetLibrary.LEONARDO().bitmapData); gingerFactory.register("leonardo", player); player = processTurtleGinger(new AssetLibrary.MICHELANGELO().bitmapData); gingerFactory.register("michelangelo", player); player = processTurtleGinger(new AssetLibrary.RAPHAEL().bitmapData); gingerFactory.register("raphael", player); player = processTurtleGinger(new AssetLibrary.DONATELLO().bitmapData); gingerFactory.register("donatello", player); bitmapData = new AssetLibrary.FS_SWORD().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); animation.isLooping = true; player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 3, 0, (sz * 2)); player.addAnimation("windup", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 2), (sz * 2)); player.addAnimation("stall", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 3, (sz * 3), (sz * 2)); animation.changeFrameID(1, "attackStart"); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 3)); animation.changeFrameID(5, "death_final"); player.addAnimation("death", animation); gingerFactory.register("sword_ninja", player); bitmapData = new AssetLibrary.LASER_NINJA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 4, 0, (0 * 128)); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 2, (4 * 128)); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 6, 0, (1 * 128)); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 6, 0, (2 * 128)); player.addAnimation("death", animation); gingerFactory.register("laser_ninja", player); sz = 128; bitmapData = new AssetLibrary.SENTRY().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (0 * 128)); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (1 * 128)); animation.isLooping = true; player.addAnimation("active", animation); animation = AnimationBuilder.importStrip(fastFps, bitmapData, sz, sz, 4, 0, (2 * 128)); player.addAnimation("death", animation); gingerFactory.register("sentry", player); sz = 64; bitmapData = new AssetLibrary.MOUSER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 1)); animation.isLooping = true; player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, 0); player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 2)); player.addAnimation("death", animation); gingerFactory.register("mouser", player); sz = 128; bitmapData = new AssetLibrary.SHURIKEN_NINJA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (4 * sz)); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (1 * sz)); animation.changeFrameID(3, "release"); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (2 * sz)); player.addAnimation("death", animation); gingerFactory.register("shuriken_ninja", player); sz = 128; bitmapData = new AssetLibrary.BLOWGUN_NINJA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, 0, 0, 1, 0, 24); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (1 * sz), 1, 0, 24); animation.changeFrameID(2, "release"); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (2 * sz), 1, 0, 24); player.addAnimation("death", animation); gingerFactory.register("blowgun_ninja", player); sz = 128; bitmapData = new AssetLibrary.JUMPING_NINJA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); animation.isLooping = true; player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 3, 0, (sz * 2)); player.addAnimation("jump", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (3 * sz), (sz * 2)); player.addAnimation("apex", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 2), (sz * 2)); player.addAnimation("fall", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 3)); player.addAnimation("death", animation); gingerFactory.register("jumping_ninja", player); var shredderAirAttackVerticalOffset = -10; sz = 128; bitmapData = new AssetLibrary.SHREDDER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, 0); player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 5), 0); animation.isLooping = true; player.addAnimation("stun", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 2)); player.addAnimation("dash", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), (sz * 2)); player.addAnimation("jump", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 3), 1, 0, shredderAirAttackVerticalOffset); player.addAnimation("airkick", animation); animation = AnimationBuilder.importStrip(4, bitmapData, sz, sz, 2, (sz * 4), (sz * 3)); animation.changeFrameID(1, "punch_1"); player.addAnimation("punch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 4)); player.addAnimation("death", animation); gingerFactory.register("shredder", player); bitmapData = new AssetLibrary.SUPER_SHREDDER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, 0); player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 5), 0); animation.isLooping = true; player.addAnimation("stun", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 2)); player.addAnimation("dash", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), (sz * 2)); player.addAnimation("jump", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 3), 1, 0, shredderAirAttackVerticalOffset); player.addAnimation("airkick", animation); animation = AnimationBuilder.importStrip(8, bitmapData, sz, sz, 2, (sz * 4), (sz * 3)); animation.changeFrameID(1, "punch_1"); player.addAnimation("punch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 4)); player.addAnimation("death", animation); gingerFactory.register("super_shredder", player); sz = 160; bitmapData = new AssetLibrary.HUN().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, 0); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); animation.isLooping = true; animation.changeFrameID(1, "step1"); animation.changeFrameID(4, "step2"); player.addAnimation("run", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 2)); animation.isLooping = true; player.addAnimation("charge", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), (sz * 2)); player.addAnimation("wallstun", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 3)); animation.changeFrameID(3, "end"); player.addAnimation("pump", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 5, 0, (sz * 4)); animation.changeFrameID(3, "punch_1"); player.addAnimation("punch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 5), 1, -20, 0); animation.isLooping = true; player.addAnimation("stunned", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4, 0, (sz * 6), 1, 0, -32); animation.changeFrameCount(3, 40); player.addAnimation("death", animation); gingerFactory.register("hun", player); sz = 160; bitmapData = new AssetLibrary.JUGGERNAUGHT().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, sz); animation.isLooping = true; player.addAnimation("walk", animation); animation = AnimationBuilder.importStrip(32, bitmapData, sz, sz, 3, 0, (sz * 2)); player.addAnimation("windup", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, (sz * 2), (sz * 2)); player.addAnimation("stall", animation); animation = AnimationBuilder.importStrip(32, bitmapData, sz, sz, 3, (sz * 3), (sz * 2)); animation.changeFrameID(1, "attackStart"); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 6, 0, (sz * 3)); player.addAnimation("death", animation); gingerFactory.register("juggernaught", player); sz = 128; bitmapData = new AssetLibrary.SLOTH().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 2, (sz * 4), 0); player.addAnimation("flinch", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 8, 0, (1 * sz)); animation.changeFrameID(5, "pound"); player.addAnimation("attack", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 8, 0, (2 * sz)); player.addAnimation("death", animation); gingerFactory.register("sloth", player); bitmapData = new AssetLibrary.SHURIKEN().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 13, 7); player.addAnimation("idle", animation); gingerFactory.register("shuriken", player); bitmapData = new AssetLibrary.DART().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 10, 4); player.addAnimation("idle", animation); gingerFactory.register("dart", player); bitmapData = new AssetLibrary.LASER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 4, 360, 4); player.addAnimation("idle", animation); gingerFactory.register("laser", player); bitmapData = new AssetLibrary.SWITCH().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(24, bitmapData, 64, 64, 1); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(24, bitmapData, 64, 64, 2, 64); player.addAnimation("switch", animation); animation = AnimationBuilder.importStrip(24, bitmapData, 64, 64, 1, 128); animation.isLooping = true; player.addAnimation("switched", animation); gingerFactory.register("switch", player); bitmapData = new AssetLibrary.JUMP_DUST().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(24, bitmapData, 64, 64, 4, 0, 0, 1, 0, -28); player.addAnimation("default", animation); gingerFactory.register("jump_dust", player); sz = 64; bitmapData = new AssetLibrary.CRUMBLING_BLOCK().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, sz, sz, 4, 0, (0 * sz), 1, 0, -32); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, sz, sz, 4, 0, (1 * sz), 1, 0, -32); player.addAnimation("disintegrate", animation); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, sz, sz, 4, 0, (2 * sz), 1, 0, -32); player.addAnimation("regrow", animation); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, sz, sz, 4, 0, (3 * sz), 1, 0, -32); animation.isLooping = true; player.addAnimation("idle_disintegrated", animation); gingerFactory.register("crumbling_block", player); bitmapData = new AssetLibrary.BREAKABLE_WALL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 1, 0, 0, 1); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 1, 48, 0, 1); animation.isLooping = true; player.addAnimation("damaged-1", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 1, (48 * 2), 0, 1); animation.isLooping = true; player.addAnimation("damaged-2", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 1, (48 * 3), 0, 1); animation.isLooping = true; player.addAnimation("damaged-3", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 4, 0, 96, 1, 0, 0); player.addAnimation("death", animation); gingerFactory.register("breakable_wall", player); bitmapData = new AssetLibrary.DRILL_BOX().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, new BitmapData(5, 5, true, 0), 5, 5, 1, 0, 0, 1, 0, 0); player.addAnimation("waiting", animation); animation = AnimationBuilder.importStrip((2 * fps), bitmapData, 96, 128, 10, 0, 0, 1, 0, 0); player.addAnimation("arrive", animation); animation = AnimationBuilder.importStrip((2 * fps), bitmapData, 96, 128, 10, 0, 0, 1, 0, 0); animation.reverseFrames(); player.addAnimation("death", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 96, 128, 1, (96 * 9), 0, 1, 0, 0); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 96, 128, 1, (96 * 9), 0, 1, 0, 0); player.addAnimation("flinch", animation); gingerFactory.register("drill_box", player); bitmapData = new AssetLibrary.ELECTRICAL_WALL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 48, 96, 4, 0, 0, 1, 0, 0); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("electrical_wall", player); bitmapData = new AssetLibrary.PLATFORM().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 64, 42, 4, 0, 0, 1, 0, 16); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("platform", player); bitmapData = new AssetLibrary.SPECIAL_MICHELANGELO().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(10, bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("special_michelangelo", player); bitmapData = new AssetLibrary.SPECIAL_RAPHAEL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(10, bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("special_raphael", player); bitmapData = new AssetLibrary.SPECIAL_CASEY_JONES().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(10, bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("special_casey_jones", player); bitmapData = new AssetLibrary.DONATELLO_TILE().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 240, 240, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("donatello_tile", player); bitmapData = new AssetLibrary.DONATELLO_TRAIL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 240, 240, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("donatello_trail", player); bitmapData = new AssetLibrary.LEONARDO_TILE().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 240, 240, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("leonardo_tile", player); bitmapData = new AssetLibrary.LEONARDO_TRAIL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 240, 240, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("leonardo_trail", player); bitmapData = new AssetLibrary.SPECIAL_LEONARDO().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 160, 120, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("special_leonardo", player); bitmapData = new AssetLibrary.SPECIAL_DONATELLO().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("default", animation); gingerFactory.register("special_donatello", player); bitmapData = new AssetLibrary.SPECIAL_PIZZA_DELIVERY().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("carrying", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, 128, 128, 4, 0, 128); animation.isLooping = true; player.addAnimation("dropped", animation); gingerFactory.register("special_pizza_dude", player); bitmapData = new AssetLibrary.SPECIAL_SPLINTER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip((3 * fps), new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, 128, 128, 4); animation.isLooping = true; player.addAnimation("idle", animation); animation = AnimationBuilder.importStrip((3 * fps), bitmapData, 128, 128, 4, (4 * 128)); player.addAnimation("attack", animation); gingerFactory.register("special_splinter", player); sz = 220; bitmapData = new AssetLibrary.KANJI_ATTACK().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip((3 * fps), new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 8); player.addAnimation("attack", animation); gingerFactory.register("kanji_attack", player); sz = 220; bitmapData = new AssetLibrary.KANJI_NINJA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip((3 * fps), new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 8); player.addAnimation("attack", animation); gingerFactory.register("kanji_ninja", player); sz = 220; bitmapData = new AssetLibrary.KANJI_RAT().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip((3 * fps), new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 8); player.addAnimation("attack", animation); gingerFactory.register("kanji_rat", player); sz = 24; bitmapData = new AssetLibrary.SHELL_CELL().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("shell_cell", player); sz = 24; bitmapData = new AssetLibrary.OOZE_CANNISTER().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("ooze_cannister", player); sz = 24; bitmapData = new AssetLibrary.OOZE_CAN().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("ooze_drop", player); sz = 24; bitmapData = new AssetLibrary.PIZZA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("pizza_slice", player); sz = 24; bitmapData = new AssetLibrary.FULL_PIZZA().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("full_pizza", player); sz = 20; bitmapData = new AssetLibrary.MUTE_BUTTON().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1); animation.isLooping = true; player.addAnimation("unmuted", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, sz, 1, sz); animation.isLooping = true; player.addAnimation("muted", animation); gingerFactory.register("mute_button", player); sz = 72; bitmapData = new AssetLibrary.EXIT_TURTLE().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, 64, 96, 4); animation.isLooping = true; player.addAnimation("idle", animation); gingerFactory.register("exit", player); sz = 27; bitmapData = new AssetLibrary.LEVEL_MARKERS().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, 56, 1, (0 * sz)); animation.isLooping = true; player.addAnimation("story", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, 56, 1, (1 * sz)); animation.isLooping = true; player.addAnimation("boss", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, 56, 1, (2 * sz)); animation.isLooping = true; player.addAnimation("combat", animation); animation = AnimationBuilder.importStrip(fps, bitmapData, sz, 56, 1, (3 * sz)); animation.isLooping = true; player.addAnimation("platformer", animation); gingerFactory.register("level_marker", player); sz = 64; bitmapData = new AssetLibrary.HIT_EFFECT_1().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip((4 * fps), bitmapData, sz, sz, 4); player.addAnimation("default", animation); gingerFactory.register("hit_effect_1", player); sz = 64; bitmapData = new AssetLibrary.HIT_EFFECT_2().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip((4 * fps), bitmapData, sz, sz, 4); player.addAnimation("default", animation); gingerFactory.register("hit_effect_2", player); sz = 64; bitmapData = new AssetLibrary.HIT_EFFECT_3().bitmapData; player = new AnimationPlayer(); animation = AnimationBuilder.importStrip(fps, new BitmapData(1, 1, true, 0), 1, 1, 1); animation.isLooping = true; player.addAnimation("blank", animation); animation = AnimationBuilder.importStrip((4 * fps), bitmapData, sz, sz, 4); player.addAnimation("default", animation); gingerFactory.register("hit_effect_3", player); } } }//package
Section 414
//MochiBot (MochiBot) package { import flash.events.*; import flash.display.*; import flash.net.*; import flash.system.*; public dynamic class MochiBot extends Sprite { public function MochiBot(){ super(); } private static function handleError(a_event:Event):void{ } public static function track(parent:Sprite, tag:String):MochiBot{ if (Security.sandboxType == "localWithFile"){ return (null); }; var self:MochiBot = new (MochiBot); parent.addChild(self); Security.allowDomain("*"); Security.allowInsecureDomain("*"); var server:String = "http://core.mochibot.com/my/core.swf"; var lv:URLVariables = new URLVariables(); lv["sb"] = Security.sandboxType; lv["v"] = Capabilities.version; lv["swfid"] = tag; lv["mv"] = "8"; lv["fv"] = "9"; var url:String = self.root.loaderInfo.loaderURL; if (url.indexOf("http") == 0){ lv["url"] = url; } else { lv["url"] = "local"; }; var req:URLRequest = new URLRequest(server); req.contentType = "application/x-www-form-urlencoded"; req.method = URLRequestMethod.POST; req.data = lv; var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleError); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleError); self.addChild(loader); loader.load(req); return (self); } } }//package
Section 415
//MouserChompNoise1 (MouserChompNoise1) package { import flash.media.*; public dynamic class MouserChompNoise1 extends Sound { } }//package
Section 416
//MUSIC_BOSS (MUSIC_BOSS) package { import flash.media.*; public dynamic class MUSIC_BOSS extends Sound { } }//package
Section 417
//MUSIC_IN_GAME (MUSIC_IN_GAME) package { import flash.media.*; public dynamic class MUSIC_IN_GAME extends Sound { } }//package
Section 418
//MUSIC_UI (MUSIC_UI) package { import flash.media.*; public dynamic class MUSIC_UI extends Sound { } }//package
Section 419
//MyPreloader (MyPreloader) package { import flash.text.*; public class MyPreloader extends Preloader { private var m_textfield:TextField; public function MyPreloader(){ super(); } override protected function updateLoading(a_percent:Number):void{ m_textfield.text = (("Loading: " + Math.round((a_percent * 100))) + "%"); } override protected function endLoading():void{ removeChild(m_textfield); m_textfield = null; } override protected function beginLoading():void{ m_textfield = new TextField(); m_textfield.autoSize = TextFieldAutoSize.RIGHT; m_textfield.textColor = 0xFFFFFF; m_textfield.text = "0%"; m_textfield.x = 345; m_textfield.y = 205; addChild(m_textfield); } } }//package
Section 420
//next_button_mc (next_button_mc) package { import flash.display.*; public dynamic class next_button_mc extends MovieClip { } }//package
Section 421
//PizzaPowerUp (PizzaPowerUp) package { import flash.media.*; public dynamic class PizzaPowerUp extends Sound { } }//package
Section 422
//Preloader (Preloader) package { import flash.events.*; import flash.display.*; import flash.utils.*; public class Preloader extends MovieClip { private var m_firstFrame:Boolean;// = true public function Preloader(){ super(); addEventListener(Event.ENTER_FRAME, checkFrame); } protected function endLoading():void{ } protected function updateLoading(a_percent:Number):void{ } private function checkFrame(e:Event):void{ if (currentFrame == totalFrames){ removeEventListener(Event.ENTER_FRAME, checkFrame); startup(); return; }; if (m_firstFrame){ beginLoading(); m_firstFrame = false; return; }; var percent:Number = (root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal); updateLoading(percent); } protected function get mainClassName():String{ return ("Main"); } protected function beginLoading():void{ } private function startup():void{ stop(); if (!m_firstFrame){ endLoading(); }; var MainClass:Class = (getDefinitionByName(mainClassName) as Class); if (MainClass == null){ throw (new Error((("Preloader:startup. There was no class matching [" + mainClassName) + "]. You may need to override Preloader::mainClassName"))); }; var main:DisplayObject = (new (MainClass) as DisplayObject); if (main == null){ throw (new Error((("Preloader::startup. [" + mainClassName) + "] needs to inherit from Sprite or MovieClip."))); }; addChildAt(main, 0); } } }//package
Section 423
//ProlongingLaserBeam1 (ProlongingLaserBeam1) package { import flash.media.*; public dynamic class ProlongingLaserBeam1 extends Sound { } }//package
Section 424
//SentryActivate (SentryActivate) package { import flash.media.*; public dynamic class SentryActivate extends Sound { } }//package
Section 425
//ShellAttack (ShellAttack) package { import flash.media.*; public dynamic class ShellAttack extends Sound { } }//package
Section 426
//ShortLaserChargeUp1 (ShortLaserChargeUp1) package { import flash.media.*; public dynamic class ShortLaserChargeUp1 extends Sound { } }//package
Section 427
//ShredderAirDash (ShredderAirDash) package { import flash.media.*; public dynamic class ShredderAirDash extends Sound { } }//package
Section 428
//ShredderSlide (ShredderSlide) package { import flash.media.*; public dynamic class ShredderSlide extends Sound { } }//package
Section 429
//ShurikenBlowDartThrowNoise1 (ShurikenBlowDartThrowNoise1) package { import flash.media.*; public dynamic class ShurikenBlowDartThrowNoise1 extends Sound { } }//package
Section 430
//SlothPound (SlothPound) package { import flash.media.*; public dynamic class SlothPound extends Sound { } }//package
Section 431
//SmallJumpNoise1 (SmallJumpNoise1) package { import flash.media.*; public dynamic class SmallJumpNoise1 extends Sound { } }//package
Section 432
//SpecialAttackActivationNoise1 (SpecialAttackActivationNoise1) package { import flash.media.*; public dynamic class SpecialAttackActivationNoise1 extends Sound { } }//package
Section 433
//StrongPunchAttack1 (StrongPunchAttack1) package { import flash.media.*; public dynamic class StrongPunchAttack1 extends Sound { } }//package
Section 434
//tmnt_page01_mc (tmnt_page01_mc) package { import flash.events.*; import flash.display.*; public dynamic class tmnt_page01_mc extends MovieClip { public var nextBtn:MovieClip; public function tmnt_page01_mc(){ addFrameScript(0, frame1, 84, frame85, 85, frame86, 185, frame186, 186, frame187, 265, frame266); } function frame86(){ nextBtn.visible = false; } function frame85(){ nextBtn.visible = true; stop(); } function frame187(){ nextBtn.visible = false; } function frame1(){ nextBtn = new next_button_mc(); nextBtn.visible = false; nextBtn.buttonMode = true; nextBtn.x = ((stage.stageWidth - nextBtn.width) - 5); nextBtn.y = ((stage.stageHeight - nextBtn.height) - 5); nextBtn.addEventListener(MouseEvent.CLICK, clickHandler); addChild(nextBtn); } function frame186(){ nextBtn.visible = true; stop(); } public function onRemoved(_arg1:Event):void{ trace(" onRemoved: cleanup listeners"); nextBtn.removeEventListener(MouseEvent.CLICK, clickHandler); nextBtn = null; removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved); } public function clickHandler(_arg1:MouseEvent):void{ trace(" clickHandler: go to next panel"); play(); } function frame266(){ stop(); } } }//package
Section 435
//tmnt_page02_mc (tmnt_page02_mc) package { import flash.events.*; import flash.display.*; public dynamic class tmnt_page02_mc extends MovieClip { public var nextBtn:MovieClip; public function tmnt_page02_mc(){ addFrameScript(0, frame1, 109, frame110, 110, frame111, 181, frame182, 182, frame183, 264, frame265); } function frame265(){ stop(); } function frame183(){ nextBtn.visible = false; } function frame1(){ nextBtn = new next_button_mc(); nextBtn.visible = false; nextBtn.buttonMode = true; nextBtn.x = ((stage.stageWidth - nextBtn.width) - 5); nextBtn.y = ((stage.stageHeight - nextBtn.height) - 5); nextBtn.addEventListener(MouseEvent.CLICK, clickHandler); addChild(nextBtn); } function frame182(){ nextBtn.visible = true; stop(); } function frame110(){ nextBtn.visible = true; stop(); } function frame111(){ nextBtn.visible = false; } public function onRemoved(_arg1:Event):void{ trace(" onRemoved: cleanup listeners"); nextBtn.removeEventListener(MouseEvent.CLICK, clickHandler); nextBtn = null; removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved); } public function clickHandler(_arg1:MouseEvent):void{ trace(" clickHandler: go to next panel"); play(); } } }//package
Section 436
//tmnt_page02b_mc (tmnt_page02b_mc) package { import flash.events.*; import flash.display.*; public dynamic class tmnt_page02b_mc extends MovieClip { public var nextBtn:MovieClip; public function tmnt_page02b_mc(){ addFrameScript(0, frame1, 79, frame80, 80, frame81, 164, frame165, 165, frame166, 279, frame280); } function frame165(){ nextBtn.visible = true; stop(); } function frame80(){ nextBtn.visible = true; stop(); } function frame166(){ nextBtn.visible = false; } function frame280(){ stop(); } function frame81(){ nextBtn.visible = false; } function frame1(){ nextBtn = new next_button_mc(); nextBtn.visible = false; nextBtn.buttonMode = true; nextBtn.x = ((stage.stageWidth - nextBtn.width) - 5); nextBtn.y = ((stage.stageHeight - nextBtn.height) - 5); nextBtn.addEventListener(MouseEvent.CLICK, clickHandler); addChild(nextBtn); } public function onRemoved(_arg1:Event):void{ trace(" onRemoved: cleanup listeners"); nextBtn.removeEventListener(MouseEvent.CLICK, clickHandler); nextBtn = null; removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved); } public function clickHandler(_arg1:MouseEvent):void{ trace(" clickHandler: go to next panel"); play(); } } }//package
Section 437
//tmnt_page04_mc (tmnt_page04_mc) package { import flash.events.*; import flash.display.*; public dynamic class tmnt_page04_mc extends MovieClip { public var nextBtn:MovieClip; public function tmnt_page04_mc(){ addFrameScript(0, frame1, 54, frame55, 55, frame56, 114, frame115, 115, frame116, 304, frame305); } function frame305(){ stop(); } function frame1(){ nextBtn = new next_button_mc(); nextBtn.visible = false; nextBtn.buttonMode = true; nextBtn.x = ((stage.stageWidth - nextBtn.width) - 5); nextBtn.y = ((stage.stageHeight - nextBtn.height) - 5); nextBtn.addEventListener(MouseEvent.CLICK, clickHandler); addChild(nextBtn); } public function onRemoved(_arg1:Event):void{ trace(" onRemoved: cleanup listeners"); nextBtn.removeEventListener(MouseEvent.CLICK, clickHandler); nextBtn = null; removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved); } function frame115(){ setChildIndex(nextBtn, (numChildren - 1)); nextBtn.visible = true; stop(); } function frame116(){ nextBtn.visible = false; } public function clickHandler(_arg1:MouseEvent):void{ trace(" clickHandler: go to next panel"); play(); } function frame55(){ nextBtn.visible = true; stop(); } function frame56(){ nextBtn.visible = false; } } }//package
Section 438
//TurtleDie (TurtleDie) package { import flash.media.*; public dynamic class TurtleDie extends Sound { } }//package
Section 439
//TurtleHitGrunt1 (TurtleHitGrunt1) package { import flash.media.*; public dynamic class TurtleHitGrunt1 extends Sound { } }//package
Section 440
//WallSlide (WallSlide) package { import flash.media.*; public dynamic class WallSlide extends Sound { } }//package
Section 441
//Zap (Zap) package { import flash.media.*; public dynamic class Zap extends Sound { } }//package

Library Items

Symbol 1 Sound {SentryActivate} [SentryActivate]
Symbol 2 Sound {FootSoldierHit} [FootSoldierHit]
Symbol 3 Sound {ShurikenBlowDartThrowNoise1} [ShurikenBlowDartThrowNoise1]
Symbol 4 Sound {FootSoldierHit2} [FootSoldierHit2]
Symbol 5 Sound {HitNoiseForRobots1} [HitNoiseForRobots1]
Symbol 6 Sound {GainingOozeNoise2} [GainingOozeNoise2]
Symbol 7 Sound {FootSoldierHit3} [FootSoldierHit3]
Symbol 8 Sound {MUSIC_IN_GAME} [MUSIC_IN_GAME]
Symbol 9 Sound {MUSIC_UI} [MUSIC_UI]
Symbol 10 Sound {MUSIC_BOSS} [MUSIC_BOSS]
Symbol 11 Sound {MouserChompNoise1} [MouserChompNoise1]
Symbol 12 Sound {ShellAttack} [ShellAttack]
Symbol 13 Sound {PizzaPowerUp} [PizzaPowerUp]
Symbol 14 Sound {Zap} [Zap]
Symbol 15 Sound {BreakableWall} [BreakableWall]
Symbol 16 Sound {HunHuff} [HunHuff]
Symbol 17 Sound {HunStep} [HunStep]
Symbol 18 Sound {HunHitWall} [HunHitWall]
Symbol 19 Sound {StrongPunchAttack1} [StrongPunchAttack1]
Symbol 20 Sound {WallSlide} [WallSlide]
Symbol 21 Sound {HunDie} [HunDie]
Symbol 22 Sound {FootSoldierDie2} [FootSoldierDie2]
Symbol 23 Sound {FootSoldierDie} [FootSoldierDie]
Symbol 24 Sound {MachineDie1} [MachineDie1]
Symbol 25 Sound {BluntSwingNoise1} [BluntSwingNoise1]
Symbol 26 Sound {BladeSwipeNoise1} [BladeSwipeNoise1]
Symbol 27 Sound {SpecialAttackActivationNoise1} [SpecialAttackActivationNoise1]
Symbol 28 Sound {TurtleDie} [TurtleDie]
Symbol 29 Sound {Buzz} [Buzz]
Symbol 30 Sound {SmallJumpNoise1} [SmallJumpNoise1]
Symbol 31 Sound {TurtleHitGrunt1} [TurtleHitGrunt1]
Symbol 32 Sound {DrillBox} [DrillBox]
Symbol 33 Sound {ShortLaserChargeUp1} [ShortLaserChargeUp1]
Symbol 34 Sound {ProlongingLaserBeam1} [ProlongingLaserBeam1]
Symbol 35 Sound {ShredderSlide} [ShredderSlide]
Symbol 36 Sound {ShredderAirDash} [ShredderAirDash]
Symbol 37 Sound {JumpingNinjaJump} [JumpingNinjaJump]
Symbol 38 Sound {SlothPound} [SlothPound]
Symbol 39 GraphicUsed by:40
Symbol 40 MovieClipUses:39Used by:94 104 120 130 165 191 209 217 227 230 238
Symbol 41 GraphicUsed by:50 75 93
Symbol 42 BitmapUsed by:43
Symbol 43 GraphicUses:42Used by:50
Symbol 44 BitmapUsed by:45
Symbol 45 GraphicUses:44Used by:50
Symbol 46 GraphicUsed by:50
Symbol 47 FontUsed by:48 66 69 73 99 102 118 125 128 140 145 184 189 202 215 222 225 236 241
Symbol 48 TextUses:47Used by:50
Symbol 49 GraphicUsed by:50
Symbol 50 MovieClip {tmnt_comic_panels_cs3_fla.page01_panel01_60} [tmnt_comic_panels_cs3_fla.page01_panel01_60]Uses:41 43 45 46 48 49Used by:94
Symbol 51 BitmapUsed by:52
Symbol 52 GraphicUses:51Used by:53
Symbol 53 MovieClipUses:52Used by:75
Symbol 54 BitmapUsed by:55
Symbol 55 GraphicUses:54Used by:56
Symbol 56 MovieClipUses:55Used by:75
Symbol 57 BitmapUsed by:58
Symbol 58 GraphicUses:57Used by:61
Symbol 59 GraphicUsed by:60
Symbol 60 MovieClipUses:59Used by:61
Symbol 61 MovieClip {tmnt_comic_panels_cs3_fla.p01_64} [tmnt_comic_panels_cs3_fla.p01_64]Uses:58 60Used by:75
Symbol 62 BitmapUsed by:63
Symbol 63 GraphicUses:62Used by:64
Symbol 64 MovieClipUses:63Used by:75
Symbol 65 GraphicUsed by:67
Symbol 66 TextUses:47Used by:67
Symbol 67 MovieClipUses:65 66Used by:71
Symbol 68 GraphicUsed by:70
Symbol 69 TextUses:47Used by:70
Symbol 70 MovieClipUses:68 69Used by:71
Symbol 71 MovieClip {tmnt_comic_panels_cs3_fla.p01_67} [tmnt_comic_panels_cs3_fla.p01_67]Uses:67 70Used by:75
Symbol 72 GraphicUsed by:74
Symbol 73 TextUses:47Used by:74
Symbol 74 MovieClipUses:72 73Used by:75
Symbol 75 MovieClip {tmnt_comic_panels_cs3_fla.page01_panel02_61} [tmnt_comic_panels_cs3_fla.page01_panel02_61]Uses:41 53 56 61 64 71 74Used by:94
Symbol 76 GraphicUsed by:93
Symbol 77 GraphicUsed by:93
Symbol 78 BitmapUsed by:79
Symbol 79 GraphicUses:78Used by:80
Symbol 80 MovieClipUses:79Used by:93
Symbol 81 GraphicUsed by:93
Symbol 82 BitmapUsed by:83
Symbol 83 GraphicUses:82Used by:84
Symbol 84 MovieClipUses:83Used by:93
Symbol 85 BitmapUsed by:86
Symbol 86 GraphicUses:85Used by:87
Symbol 87 MovieClipUses:86Used by:93
Symbol 88 BitmapUsed by:89
Symbol 89 GraphicUses:88Used by:90
Symbol 90 MovieClipUses:89Used by:93
Symbol 91 GraphicUsed by:92
Symbol 92 MovieClipUses:91Used by:93
Symbol 93 MovieClip {tmnt_comic_panels_cs3_fla.page01_panel03_71} [tmnt_comic_panels_cs3_fla.page01_panel03_71]Uses:76 77 80 81 84 87 90 92 41Used by:94
Symbol 94 MovieClip {tmnt_page01_mc} [tmnt_page01_mc]Uses:40 50 75 93
Symbol 95 BitmapUsed by:96
Symbol 96 GraphicUses:95Used by:97
Symbol 97 MovieClipUses:96Used by:104
Symbol 98 GraphicUsed by:100
Symbol 99 TextUses:47Used by:100
Symbol 100 MovieClipUses:98 99Used by:104
Symbol 101 GraphicUsed by:103
Symbol 102 TextUses:47Used by:103
Symbol 103 MovieClipUses:101 102Used by:104
Symbol 104 MovieClip {tmnt_comic_panels_cs3_fla.p05_2} [tmnt_comic_panels_cs3_fla.p05_2]Uses:40 97 100 103Used by:133
Symbol 105 BitmapUsed by:106
Symbol 106 GraphicUses:105Used by:107
Symbol 107 MovieClipUses:106Used by:120
Symbol 108 BitmapUsed by:109
Symbol 109 GraphicUses:108Used by:110
Symbol 110 MovieClipUses:109Used by:120
Symbol 111 BitmapUsed by:112
Symbol 112 GraphicUses:111Used by:113
Symbol 113 MovieClipUses:112Used by:120
Symbol 114 BitmapUsed by:115
Symbol 115 GraphicUses:114Used by:116
Symbol 116 MovieClipUses:115Used by:120
Symbol 117 GraphicUsed by:119
Symbol 118 TextUses:47Used by:119
Symbol 119 MovieClipUses:117 118Used by:120
Symbol 120 MovieClip {tmnt_comic_panels_cs3_fla.p05_7} [tmnt_comic_panels_cs3_fla.p05_7]Uses:40 107 110 113 116 119Used by:133
Symbol 121 BitmapUsed by:122
Symbol 122 GraphicUses:121Used by:123
Symbol 123 MovieClipUses:122Used by:130
Symbol 124 GraphicUsed by:126
Symbol 125 TextUses:47Used by:126
Symbol 126 MovieClipUses:124 125Used by:130
Symbol 127 GraphicUsed by:129
Symbol 128 TextUses:47Used by:129
Symbol 129 MovieClipUses:127 128Used by:130
Symbol 130 MovieClip {tmnt_comic_panels_cs3_fla.p05_13} [tmnt_comic_panels_cs3_fla.p05_13]Uses:40 123 126 129Used by:133
Symbol 131 FontUsed by:132
Symbol 132 TextUses:131Used by:133
Symbol 133 MovieClip {tmnt_page04_mc} [tmnt_page04_mc]Uses:104 120 130 132
Symbol 134 BitmapUsed by:135
Symbol 135 GraphicUses:134Used by:136
Symbol 136 MovieClipUses:135Used by:165
Symbol 137 BitmapUsed by:138
Symbol 138 GraphicUses:137Used by:141
Symbol 139 GraphicUsed by:141
Symbol 140 TextUses:47Used by:141
Symbol 141 MovieClip {tmnt_comic_panels_cs3_fla.p02_34} [tmnt_comic_panels_cs3_fla.p02_34]Uses:138 139 140Used by:165
Symbol 142 BitmapUsed by:143
Symbol 143 GraphicUses:142Used by:146
Symbol 144 GraphicUsed by:146
Symbol 145 TextUses:47Used by:146
Symbol 146 MovieClip {tmnt_comic_panels_cs3_fla.p02_35} [tmnt_comic_panels_cs3_fla.p02_35]Uses:143 144 145Used by:165
Symbol 147 BitmapUsed by:148
Symbol 148 GraphicUses:147Used by:149
Symbol 149 MovieClipUses:148Used by:165
Symbol 150 BitmapUsed by:151
Symbol 151 GraphicUses:150Used by:152
Symbol 152 MovieClipUses:151Used by:165
Symbol 153 BitmapUsed by:154
Symbol 154 GraphicUses:153Used by:155
Symbol 155 MovieClipUses:154Used by:165
Symbol 156 BitmapUsed by:157
Symbol 157 GraphicUses:156Used by:158
Symbol 158 MovieClipUses:157Used by:165
Symbol 159 BitmapUsed by:160
Symbol 160 GraphicUses:159Used by:161
Symbol 161 MovieClipUses:160Used by:165
Symbol 162 BitmapUsed by:163
Symbol 163 GraphicUses:162Used by:164
Symbol 164 MovieClipUses:163Used by:165
Symbol 165 MovieClip {tmnt_comic_panels_cs3_fla.p02_32} [tmnt_comic_panels_cs3_fla.p02_32]Uses:40 136 141 146 149 152 155 158 161 164Used by:210
Symbol 166 BitmapUsed by:167
Symbol 167 GraphicUses:166Used by:168
Symbol 168 MovieClipUses:167Used by:191
Symbol 169 BitmapUsed by:170
Symbol 170 GraphicUses:169Used by:171
Symbol 171 MovieClipUses:170Used by:191
Symbol 172 BitmapUsed by:173
Symbol 173 GraphicUses:172Used by:174
Symbol 174 MovieClipUses:173Used by:191
Symbol 175 BitmapUsed by:176
Symbol 176 GraphicUses:175Used by:177
Symbol 177 MovieClipUses:176Used by:191
Symbol 178 BitmapUsed by:179
Symbol 179 GraphicUses:178Used by:180
Symbol 180 MovieClipUses:179Used by:191
Symbol 181 BitmapUsed by:182
Symbol 182 GraphicUses:181Used by:185
Symbol 183 GraphicUsed by:185
Symbol 184 TextUses:47Used by:185
Symbol 185 MovieClip {tmnt_comic_panels_cs3_fla.p02_48} [tmnt_comic_panels_cs3_fla.p02_48]Uses:182 183 184Used by:191
Symbol 186 BitmapUsed by:187
Symbol 187 GraphicUses:186Used by:190
Symbol 188 GraphicUsed by:190
Symbol 189 TextUses:47Used by:190
Symbol 190 MovieClip {tmnt_comic_panels_cs3_fla.p02_49} [tmnt_comic_panels_cs3_fla.p02_49]Uses:187 188 189Used by:191
Symbol 191 MovieClip {tmnt_comic_panels_cs3_fla.p02_42} [tmnt_comic_panels_cs3_fla.p02_42]Uses:40 168 171 174 177 180 185 190Used by:210
Symbol 192 BitmapUsed by:193
Symbol 193 GraphicUses:192Used by:194
Symbol 194 MovieClipUses:193Used by:209
Symbol 195 BitmapUsed by:196
Symbol 196 GraphicUses:195Used by:197
Symbol 197 MovieClipUses:196Used by:209
Symbol 198 BitmapUsed by:199
Symbol 199 GraphicUses:198Used by:200
Symbol 200 MovieClipUses:199Used by:209
Symbol 201 GraphicUsed by:209
Symbol 202 TextUses:47Used by:209
Symbol 203 BitmapUsed by:204
Symbol 204 GraphicUses:203Used by:205
Symbol 205 MovieClipUses:204Used by:209
Symbol 206 BitmapUsed by:207
Symbol 207 GraphicUses:206Used by:208
Symbol 208 MovieClipUses:207Used by:209
Symbol 209 MovieClip {tmnt_comic_panels_cs3_fla.p02_50} [tmnt_comic_panels_cs3_fla.p02_50]Uses:40 194 197 200 201 202 205 208Used by:210
Symbol 210 MovieClip {tmnt_page02_mc} [tmnt_page02_mc]Uses:165 191 209
Symbol 211 BitmapUsed by:212
Symbol 212 GraphicUses:211Used by:213
Symbol 213 MovieClipUses:212Used by:217
Symbol 214 GraphicUsed by:216 237
Symbol 215 TextUses:47Used by:216
Symbol 216 MovieClipUses:214 215Used by:217
Symbol 217 MovieClip {tmnt_comic_panels_cs3_fla.p04_01_mc_18} [tmnt_comic_panels_cs3_fla.p04_01_mc_18]Uses:40 213 216Used by:239
Symbol 218 BitmapUsed by:219
Symbol 219 GraphicUses:218Used by:220
Symbol 220 MovieClipUses:219Used by:227 230
Symbol 221 GraphicUsed by:223
Symbol 222 TextUses:47Used by:223
Symbol 223 MovieClipUses:221 222Used by:227 230
Symbol 224 GraphicUsed by:226
Symbol 225 TextUses:47Used by:226
Symbol 226 MovieClipUses:224 225Used by:227 230
Symbol 227 MovieClip {tmnt_comic_panels_cs3_fla.p04_21} [tmnt_comic_panels_cs3_fla.p04_21]Uses:40 220 223 226Used by:239
Symbol 228 GraphicUsed by:229
Symbol 229 MovieClipUses:228Used by:230
Symbol 230 MovieClip {tmnt_comic_panels_cs3_fla.p04_25} [tmnt_comic_panels_cs3_fla.p04_25]Uses:40 220 226 223 229Used by:239
Symbol 231 BitmapUsed by:232
Symbol 232 GraphicUses:231Used by:235
Symbol 233 GraphicUsed by:234
Symbol 234 MovieClipUses:233Used by:235
Symbol 235 MovieClip {tmnt_comic_panels_cs3_fla.p04_28} [tmnt_comic_panels_cs3_fla.p04_28]Uses:232 234Used by:238
Symbol 236 TextUses:47Used by:237
Symbol 237 MovieClipUses:214 236Used by:238
Symbol 238 MovieClip {tmnt_comic_panels_cs3_fla.p04_27} [tmnt_comic_panels_cs3_fla.p04_27]Uses:40 235 237Used by:239
Symbol 239 MovieClip {tmnt_page02b_mc} [tmnt_page02b_mc]Uses:217 227 230 238
Symbol 240 GraphicUsed by:242
Symbol 241 TextUses:47Used by:242
Symbol 242 MovieClipUses:240 241Used by:243
Symbol 243 MovieClip {next_button_mc} [next_button_mc]Uses:242
Symbol 244 Bitmap {shared.AssetLibrary_SWITCH}
Symbol 245 BinaryData {game.LevelXMLs_LEVEL9}
Symbol 246 Bitmap {shared.AssetLibrary_JUMPING_NINJA}
Symbol 247 Bitmap {shared.AssetLibrary_KANJI_NINJA}
Symbol 248 Bitmap {shared.AssetLibrary_BTN_OVERLAY}
Symbol 249 Bitmap {shared.AssetLibrary_DRILL_BOX}
Symbol 250 Bitmap {shared.AssetLibrary_SPECIAL_MICHELANGELO}
Symbol 251 Bitmap {shared.AssetLibrary_PORTRAIT_LEONARDO}
Symbol 252 Bitmap {shared.AssetLibrary_CASEY_JONES_TRAIL}
Symbol 253 Bitmap {shared.AssetLibrary_OOZE_CAN}
Symbol 254 BinaryData {game.LevelXMLs_LEVEL1}
Symbol 255 BinaryData {game.LevelXMLs_LEVEL2}
Symbol 256 BinaryData {game.LevelXMLs_LEVEL3}
Symbol 257 BinaryData {game.LevelXMLs_LEVEL4}
Symbol 258 Bitmap {shared.AssetLibrary_SPECIAL_RAPHAEL}
Symbol 259 BinaryData {game.LevelXMLs_LEVEL5}
Symbol 260 Bitmap {shared.AssetLibrary_RAPHAEL}
Symbol 261 BinaryData {game.LevelXMLs_LEVEL6}
Symbol 262 BinaryData {game.LevelXMLs_LEVEL7}
Symbol 263 BinaryData {game.LevelXMLs_LEVEL8}
Symbol 264 Bitmap {shared.AssetLibrary_LEVEL_LOCK}
Symbol 265 Bitmap {shared.AssetLibrary_ROOF_TOP_EDGE}
Symbol 266 Bitmap {shared.AssetLibrary_OOZE_CANNISTER}
Symbol 267 Bitmap {shared.AssetLibrary_SHELL_CELL}
Symbol 268 Bitmap {shared.AssetLibrary_ELECTRICAL_WALL}
Symbol 269 Bitmap {shared.AssetLibrary_ROOF_TILESET}
Symbol 270 Bitmap {shared.AssetLibrary_MUTE_BUTTON}
Symbol 271 Bitmap {shared.AssetLibrary_HIT_EFFECT_3}
Symbol 272 Bitmap {shared.AssetLibrary_HIT_EFFECT_2}
Symbol 273 Bitmap {shared.AssetLibrary_HIT_EFFECT_1}
Symbol 274 Bitmap {shared.AssetLibrary_FS_SWORD}
Symbol 275 Bitmap {shared.AssetLibrary_MICHELANGEO_TRAIL}
Symbol 276 Bitmap {shared.AssetLibrary_LEVEL_CHECKMARK}
Symbol 277 Bitmap {shared.AssetLibrary_PANEL}
Symbol 278 Bitmap {shared.AssetLibrary_DONATELLO}
Symbol 279 Bitmap {shared.AssetLibrary_PORTRAIT_SPLINTER}
Symbol 280 Bitmap {shared.AssetLibrary_JUGGERNAUGHT}
Symbol 281 Bitmap {shared.AssetLibrary_SHURIKEN_NINJA}
Symbol 282 Bitmap {shared.AssetLibrary_INPUT_HELP}
Symbol 283 Bitmap {shared.AssetLibrary_MOUSER}
Symbol 284 Bitmap {shared.AssetLibrary_DONATELLO_TILE}
Symbol 285 Bitmap {shared.AssetLibrary_FULL_PIZZA}
Symbol 286 Bitmap {shared.AssetLibrary_CAMPAIGN_SCREEN}
Symbol 287 Bitmap {shared.AssetLibrary_ROOF_WALL}
Symbol 288 Bitmap {shared.AssetLibrary_SHREDDER}
Symbol 289 Bitmap {shared.AssetLibrary_EXIT_TURTLE}
Symbol 290 Bitmap {shared.AssetLibrary_RAPHAEL_TRAIL}
Symbol 291 Bitmap {shared.AssetLibrary_PORTRAIT_DONATELLO}
Symbol 292 Bitmap {shared.AssetLibrary_PIZZA}
Symbol 293 Bitmap {shared.AssetLibrary_SPECIAL_DONATELLO}
Symbol 294 Bitmap {shared.AssetLibrary_TITLE_LOGO}
Symbol 295 Bitmap {shared.AssetLibrary_WAREHOUSE_TILESET}
Symbol 296 BinaryData {game.LevelXMLs_LEVEL10}
Symbol 297 BinaryData {game.LevelXMLs_LEVEL11}
Symbol 298 BinaryData {game.LevelXMLs_LEVEL12}
Symbol 299 BinaryData {game.LevelXMLs_LEVEL13}
Symbol 300 BinaryData {game.LevelXMLs_LEVEL14}
Symbol 301 Bitmap {shared.AssetLibrary_EXIT_BOTTOM}
Symbol 302 BinaryData {game.LevelXMLs_LEVEL15}
Symbol 303 BinaryData {game.LevelXMLs_LEVEL16}
Symbol 304 Bitmap {shared.AssetLibrary_SIGN_BUBBLE}
Symbol 305 Bitmap {shared.AssetLibrary_KANJI_ATTACK}
Symbol 306 Bitmap {shared.AssetLibrary_PORTRAIT_CASEY_JONES}
Symbol 307 Bitmap {shared.AssetLibrary_SPECIAL_LEONARDO}
Symbol 308 Bitmap {shared.AssetLibrary_PUT_THIS_GAME}
Symbol 309 Bitmap {shared.AssetLibrary_JUMP_DUST}
Symbol 310 Bitmap {shared.AssetLibrary_STREETS_TILESET}
Symbol 311 Bitmap {shared.AssetLibrary_URBANSQUALL_BUTTON}
Symbol 312 Bitmap {shared.AssetLibrary_CRUMBLING_BLOCK}
Symbol 313 Bitmap {shared.AssetLibrary_SPECIAL_PIZZA_DELIVERY}
Symbol 314 Bitmap {shared.AssetLibrary_LEONARDO_TILE}
Symbol 315 Bitmap {shared.AssetLibrary_LEVEL_MARKERS}
Symbol 316 Bitmap {shared.AssetLibrary_KANJI_RAT}
Symbol 317 Bitmap {shared.AssetLibrary_PLATFORM}
Symbol 318 Bitmap {shared.AssetLibrary_DART}
Symbol 319 Font {shared.DefaultTextField_us_customFont}
Symbol 320 Bitmap {shared.AssetLibrary_STREET_STATIC_BG}
Symbol 321 Bitmap {shared.AssetLibrary_PACKSHOT_LARGE}
Symbol 322 Bitmap {shared.AssetLibrary_LEONARDO}
Symbol 323 Bitmap {shared.AssetLibrary_PORTRAIT_MICHELANGELO}
Symbol 324 Bitmap {shared.AssetLibrary_PACKSHOT_SMALL}
Symbol 325 Bitmap {shared.AssetLibrary_PORTRAIT_PIZZA_DUDE}
Symbol 326 Bitmap {shared.AssetLibrary_LASER}
Symbol 327 Bitmap {shared.AssetLibrary_DONATELLO_TRAIL}
Symbol 328 Bitmap {shared.AssetLibrary_PORTRAIT_RAPHAEL}
Symbol 329 Bitmap {shared.AssetLibrary_SPECIAL_CASEY_JONES}
Symbol 330 Bitmap {shared.AssetLibrary_BLOWGUN_NINJA}
Symbol 331 Bitmap {shared.AssetLibrary_SLOTH}
Symbol 332 Bitmap {shared.AssetLibrary_EXIT_OVERLAY}
Symbol 333 Bitmap {shared.AssetLibrary_ROOFTOP_STATIC_BG}
Symbol 334 Bitmap {shared.AssetLibrary_BTN_TILE9}
Symbol 335 Bitmap {shared.AssetLibrary_BREAKABLE_WALL}
Symbol 336 Bitmap {shared.AssetLibrary_ROOF_WALL_SLICK}
Symbol 337 Bitmap {shared.AssetLibrary_UBISOFT_LOGO}
Symbol 338 Bitmap {shared.AssetLibrary_SENTRY}
Symbol 339 Bitmap {shared.AssetLibrary_MICHELANGELO}
Symbol 340 Bitmap {shared.AssetLibrary_SUPER_SHREDDER}
Symbol 341 Bitmap {shared.AssetLibrary_HUN}
Symbol 342 Bitmap {shared.AssetLibrary_LEONARDO_TRAIL}
Symbol 343 Bitmap {shared.AssetLibrary_SHURIKEN}
Symbol 344 Bitmap {shared.AssetLibrary_LASER_NINJA}
Symbol 345 Bitmap {shared.AssetLibrary_SPECIAL_SPLINTER}

Special Tags

FileAttributes (69)Timeline Frame 1Access network only, Metadata present, AS3.
SWFMetaData (77)Timeline Frame 1459 bytes "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'><rdf:Description rdf:about='' xmlns ..."
ScriptLimits (65)Timeline Frame 1MaxRecursionDepth: 1000, ScriptTimeout: 60 seconds
ExportAssets (56)Timeline Frame 2Symbol 1 as "SentryActivate"
ExportAssets (56)Timeline Frame 2Symbol 2 as "FootSoldierHit"
ExportAssets (56)Timeline Frame 2Symbol 3 as "ShurikenBlowDartThrowNoise1"
ExportAssets (56)Timeline Frame 2Symbol 4 as "FootSoldierHit2"
ExportAssets (56)Timeline Frame 2Symbol 5 as "HitNoiseForRobots1"
ExportAssets (56)Timeline Frame 2Symbol 6 as "GainingOozeNoise2"
ExportAssets (56)Timeline Frame 2Symbol 7 as "FootSoldierHit3"
ExportAssets (56)Timeline Frame 2Symbol 8 as "MUSIC_IN_GAME"
ExportAssets (56)Timeline Frame 2Symbol 9 as "MUSIC_UI"
ExportAssets (56)Timeline Frame 2Symbol 10 as "MUSIC_BOSS"
ExportAssets (56)Timeline Frame 2Symbol 11 as "MouserChompNoise1"
ExportAssets (56)Timeline Frame 2Symbol 12 as "ShellAttack"
ExportAssets (56)Timeline Frame 2Symbol 13 as "PizzaPowerUp"
ExportAssets (56)Timeline Frame 2Symbol 14 as "Zap"
ExportAssets (56)Timeline Frame 2Symbol 15 as "BreakableWall"
ExportAssets (56)Timeline Frame 2Symbol 16 as "HunHuff"
ExportAssets (56)Timeline Frame 2Symbol 17 as "HunStep"
ExportAssets (56)Timeline Frame 2Symbol 18 as "HunHitWall"
ExportAssets (56)Timeline Frame 2Symbol 19 as "StrongPunchAttack1"
ExportAssets (56)Timeline Frame 2Symbol 20 as "WallSlide"
ExportAssets (56)Timeline Frame 2Symbol 21 as "HunDie"
ExportAssets (56)Timeline Frame 2Symbol 22 as "FootSoldierDie2"
ExportAssets (56)Timeline Frame 2Symbol 23 as "FootSoldierDie"
ExportAssets (56)Timeline Frame 2Symbol 24 as "MachineDie1"
ExportAssets (56)Timeline Frame 2Symbol 25 as "BluntSwingNoise1"
ExportAssets (56)Timeline Frame 2Symbol 26 as "BladeSwipeNoise1"
ExportAssets (56)Timeline Frame 2Symbol 27 as "SpecialAttackActivationNoise1"
ExportAssets (56)Timeline Frame 2Symbol 28 as "TurtleDie"
ExportAssets (56)Timeline Frame 2Symbol 29 as "Buzz"
ExportAssets (56)Timeline Frame 2Symbol 30 as "SmallJumpNoise1"
ExportAssets (56)Timeline Frame 2Symbol 31 as "TurtleHitGrunt1"
ExportAssets (56)Timeline Frame 2Symbol 32 as "DrillBox"
ExportAssets (56)Timeline Frame 2Symbol 33 as "ShortLaserChargeUp1"
ExportAssets (56)Timeline Frame 2Symbol 34 as "ProlongingLaserBeam1"
ExportAssets (56)Timeline Frame 2Symbol 35 as "ShredderSlide"
ExportAssets (56)Timeline Frame 2Symbol 36 as "ShredderAirDash"
ExportAssets (56)Timeline Frame 2Symbol 37 as "JumpingNinjaJump"
ExportAssets (56)Timeline Frame 2Symbol 38 as "SlothPound"
ExportAssets (56)Timeline Frame 2Symbol 94 as "tmnt_page01_mc"
ExportAssets (56)Timeline Frame 2Symbol 133 as "tmnt_page04_mc"
ExportAssets (56)Timeline Frame 2Symbol 210 as "tmnt_page02_mc"
ExportAssets (56)Timeline Frame 2Symbol 239 as "tmnt_page02b_mc"
ExportAssets (56)Timeline Frame 2Symbol 243 as "next_button_mc"
ExportAssets (56)Timeline Frame 2Symbol 75 as "tmnt_comic_panels_cs3_fla.page01_panel02_61"
ExportAssets (56)Timeline Frame 2Symbol 93 as "tmnt_comic_panels_cs3_fla.page01_panel03_71"
ExportAssets (56)Timeline Frame 2Symbol 50 as "tmnt_comic_panels_cs3_fla.page01_panel01_60"
ExportAssets (56)Timeline Frame 2Symbol 104 as "tmnt_comic_panels_cs3_fla.p05_2"
ExportAssets (56)Timeline Frame 2Symbol 120 as "tmnt_comic_panels_cs3_fla.p05_7"
ExportAssets (56)Timeline Frame 2Symbol 130 as "tmnt_comic_panels_cs3_fla.p05_13"
ExportAssets (56)Timeline Frame 2Symbol 191 as "tmnt_comic_panels_cs3_fla.p02_42"
ExportAssets (56)Timeline Frame 2Symbol 165 as "tmnt_comic_panels_cs3_fla.p02_32"
ExportAssets (56)Timeline Frame 2Symbol 209 as "tmnt_comic_panels_cs3_fla.p02_50"
ExportAssets (56)Timeline Frame 2Symbol 238 as "tmnt_comic_panels_cs3_fla.p04_27"
ExportAssets (56)Timeline Frame 2Symbol 230 as "tmnt_comic_panels_cs3_fla.p04_25"
ExportAssets (56)Timeline Frame 2Symbol 227 as "tmnt_comic_panels_cs3_fla.p04_21"
ExportAssets (56)Timeline Frame 2Symbol 217 as "tmnt_comic_panels_cs3_fla.p04_01_mc_18"
ExportAssets (56)Timeline Frame 2Symbol 61 as "tmnt_comic_panels_cs3_fla.p01_64"
ExportAssets (56)Timeline Frame 2Symbol 71 as "tmnt_comic_panels_cs3_fla.p01_67"
ExportAssets (56)Timeline Frame 2Symbol 185 as "tmnt_comic_panels_cs3_fla.p02_48"
ExportAssets (56)Timeline Frame 2Symbol 190 as "tmnt_comic_panels_cs3_fla.p02_49"
ExportAssets (56)Timeline Frame 2Symbol 141 as "tmnt_comic_panels_cs3_fla.p02_34"
ExportAssets (56)Timeline Frame 2Symbol 146 as "tmnt_comic_panels_cs3_fla.p02_35"
ExportAssets (56)Timeline Frame 2Symbol 235 as "tmnt_comic_panels_cs3_fla.p04_28"
EnableDebugger2 (64)Timeline Frame 131 bytes "u.$1$jd$KYgcs87KsP9d3E/bskmXh.."
DebugMX1 (63)Timeline Frame 1
SerialNumber (41)Timeline Frame 1

Labels

"MyPreloader"Frame 1
"start"Frame 2




http://swfchan.com/43/214574/info.shtml
Created: 1/11 -2018 02:02:55 Last modified: 1/11 -2018 02:02:55 Server time: 22/12 -2024 20:01:48