整理ecs框架

This commit is contained in:
yhh
2020-07-22 20:07:14 +08:00
parent 6b8569b0b5
commit 5b8f414a45
31 changed files with 1908 additions and 1239 deletions
+3
View File
@@ -0,0 +1,3 @@
# Default ignored files
/workspace.xml
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/egret-framework.iml" filepath="$PROJECT_DIR$/.idea/egret-framework.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+14 -16
View File
@@ -245,7 +245,7 @@ declare class Entity extends egret.DisplayObjectContainer {
getOrCreateComponent<T extends Component>(type: T): T; getOrCreateComponent<T extends Component>(type: T): T;
getComponent<T extends Component>(type: any): T; getComponent<T extends Component>(type: any): T;
getComponents(typeName: string | any, componentList?: any): any; getComponents(typeName: string | any, componentList?: any): any;
private onEntityTransformChanged; onEntityTransformChanged(comp: TransformComponent): void;
removeComponentForType<T extends Component>(type: any): boolean; removeComponentForType<T extends Component>(type: any): boolean;
removeComponent(component: Component): void; removeComponent(component: Component): void;
removeAllComponents(): void; removeAllComponents(): void;
@@ -300,6 +300,7 @@ declare class SceneManager {
static emitter: Emitter<CoreEvents>; static emitter: Emitter<CoreEvents>;
static content: ContentManager; static content: ContentManager;
private static _instnace; private static _instnace;
private static timerRuler;
static readonly Instance: SceneManager; static readonly Instance: SceneManager;
constructor(stage: egret.Stage); constructor(stage: egret.Stage);
static scene: Scene; static scene: Scene;
@@ -309,6 +310,8 @@ declare class SceneManager {
static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T; static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T;
static registerActiveSceneChanged(current: Scene, next: Scene): void; static registerActiveSceneChanged(current: Scene, next: Scene): void;
onSceneChanged(): void; onSceneChanged(): void;
private static startDebugUpdate;
private static endDebugUpdate;
} }
declare class Camera extends Component { declare class Camera extends Component {
private _zoom; private _zoom;
@@ -488,14 +491,10 @@ declare abstract class Collider extends Component {
registeredPhysicsBounds: Rectangle; registeredPhysicsBounds: Rectangle;
shouldColliderScaleAndRotateWithTransform: boolean; shouldColliderScaleAndRotateWithTransform: boolean;
collidesWithLayers: number; collidesWithLayers: number;
_localOffsetLength: number;
protected _isParentEntityAddedToScene: any; protected _isParentEntityAddedToScene: any;
protected _colliderRequiresAutoSizing: any; protected _colliderRequiresAutoSizing: any;
protected _localOffset: Vector2;
protected _isColliderRegistered: any; protected _isColliderRegistered: any;
readonly bounds: Rectangle; readonly bounds: Rectangle;
localOffset: Vector2;
setLocalOffset(offset: Vector2): void;
registerColliderWithPhysicsSystem(): void; registerColliderWithPhysicsSystem(): void;
unregisterColliderWithPhysicsSystem(): void; unregisterColliderWithPhysicsSystem(): void;
overlaps(other: Collider): any; overlaps(other: Collider): any;
@@ -894,6 +893,7 @@ declare class Rectangle extends egret.Rectangle {
edgeNormal: Vector2; edgeNormal: Vector2;
}; };
getClosestPointOnBoundsToOrigin(): Vector2; getClosestPointOnBoundsToOrigin(): Vector2;
setEgretRect(rect: egret.Rectangle): Rectangle;
static rectEncompassingPoints(points: Vector2[]): Rectangle; static rectEncompassingPoints(points: Vector2[]): Rectangle;
} }
declare class Vector3 { declare class Vector3 {
@@ -930,7 +930,7 @@ declare class Collisions {
static isCircleToCircle(circleCenter1: Vector2, circleRadius1: number, circleCenter2: Vector2, circleRadius2: number): boolean; static isCircleToCircle(circleCenter1: Vector2, circleRadius1: number, circleCenter2: Vector2, circleRadius2: number): boolean;
static isCircleToLine(circleCenter: Vector2, radius: number, lineFrom: Vector2, lineTo: Vector2): boolean; static isCircleToLine(circleCenter: Vector2, radius: number, lineFrom: Vector2, lineTo: Vector2): boolean;
static isCircleToPoint(circleCenter: Vector2, radius: number, point: Vector2): boolean; static isCircleToPoint(circleCenter: Vector2, radius: number, point: Vector2): boolean;
static isRectToCircle(rect: Rectangle, cPosition: Vector2, cRadius: number): boolean; static isRectToCircle(rect: egret.Rectangle, cPosition: Vector2, cRadius: number): boolean;
static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2): boolean; static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2): boolean;
static isRectToPoint(rX: number, rY: number, rW: number, rH: number, point: Vector2): boolean; static isRectToPoint(rX: number, rY: number, rW: number, rH: number, point: Vector2): boolean;
static getSector(rX: number, rY: number, rW: number, rH: number, point: Vector2): PointSectors; static getSector(rX: number, rY: number, rW: number, rH: number, point: Vector2): PointSectors;
@@ -955,22 +955,22 @@ declare class Physics {
static updateCollider(collider: Collider): void; static updateCollider(collider: Collider): void;
static debugDraw(secondsToDisplay: any): void; static debugDraw(secondsToDisplay: any): void;
} }
declare abstract class Shape { declare abstract class Shape extends egret.DisplayObject {
bounds: Rectangle; abstract bounds: Rectangle;
position: Vector2;
abstract center: Vector2; abstract center: Vector2;
abstract recalculateBounds(collider: Collider): any; abstract position: Vector2;
abstract pointCollidesWithShape(point: Vector2): CollisionResult; abstract pointCollidesWithShape(point: Vector2): CollisionResult;
abstract overlaps(other: Shape): any; abstract overlaps(other: Shape): any;
abstract collidesWithShape(other: Shape): CollisionResult; abstract collidesWithShape(other: Shape): CollisionResult;
} }
declare class Polygon extends Shape { declare class Polygon extends Shape {
points: Vector2[]; points: Vector2[];
isUnrotated: boolean;
private _polygonCenter; private _polygonCenter;
private _areEdgeNormalsDirty; private _areEdgeNormalsDirty;
protected _originalPoints: Vector2[]; protected _originalPoints: Vector2[];
center: Vector2; center: Vector2;
readonly position: Vector2;
readonly bounds: Rectangle;
_edgeNormals: Vector2[]; _edgeNormals: Vector2[];
readonly edgeNormals: Vector2[]; readonly edgeNormals: Vector2[];
isBox: boolean; isBox: boolean;
@@ -990,11 +990,8 @@ declare class Polygon extends Shape {
pointCollidesWithShape(point: Vector2): CollisionResult; pointCollidesWithShape(point: Vector2): CollisionResult;
containsPoint(point: Vector2): boolean; containsPoint(point: Vector2): boolean;
static buildSymmertricalPolygon(vertCount: number, radius: number): any[]; static buildSymmertricalPolygon(vertCount: number, radius: number): any[];
recalculateBounds(collider: Collider): void;
} }
declare class Box extends Polygon { declare class Box extends Polygon {
width: number;
height: number;
constructor(width: number, height: number); constructor(width: number, height: number);
private static buildBox; private static buildBox;
overlaps(other: Shape): any; overlaps(other: Shape): any;
@@ -1006,10 +1003,11 @@ declare class Circle extends Shape {
radius: number; radius: number;
_originalRadius: number; _originalRadius: number;
center: Vector2; center: Vector2;
readonly position: Vector2;
readonly bounds: Rectangle;
constructor(radius: number); constructor(radius: number);
pointCollidesWithShape(point: Vector2): CollisionResult; pointCollidesWithShape(point: Vector2): CollisionResult;
collidesWithShape(other: Shape): CollisionResult; collidesWithShape(other: Shape): CollisionResult;
recalculateBounds(collider: Collider): void;
overlaps(other: Shape): any; overlaps(other: Shape): any;
} }
declare class CollisionResult { declare class CollisionResult {
@@ -1062,7 +1060,6 @@ declare class RaycastResultParser {
declare class NumberDictionary { declare class NumberDictionary {
private _store; private _store;
private getKey; private getKey;
private intToUint;
add(x: number, y: number, list: Collider[]): void; add(x: number, y: number, list: Collider[]): void;
remove(obj: Collider): void; remove(obj: Collider): void;
tryGetValue(x: number, y: number): Collider[]; tryGetValue(x: number, y: number): Collider[];
@@ -1413,6 +1410,7 @@ declare class MarkerCollection {
markCount: number; markCount: number;
markerNests: number[]; markerNests: number[];
nestCount: number; nestCount: number;
constructor();
} }
declare class Marker { declare class Marker {
markerId: number; markerId: number;
+101 -107
View File
@@ -1403,6 +1403,7 @@ var SceneManager = (function () {
SceneManager.content = new ContentManager(); SceneManager.content = new ContentManager();
SceneManager.stage = stage; SceneManager.stage = stage;
SceneManager.initialize(stage); SceneManager.initialize(stage);
SceneManager.timerRuler = new TimeRuler();
} }
Object.defineProperty(SceneManager, "Instance", { Object.defineProperty(SceneManager, "Instance", {
get: function () { get: function () {
@@ -1435,6 +1436,7 @@ var SceneManager = (function () {
Input.initialize(stage); Input.initialize(stage);
}; };
SceneManager.update = function () { SceneManager.update = function () {
SceneManager.startDebugUpdate();
Time.update(egret.getTimer()); Time.update(egret.getTimer());
if (SceneManager._scene) { if (SceneManager._scene) {
for (var i = GlobalManager.globalManagers.length - 1; i >= 0; i--) { for (var i = GlobalManager.globalManagers.length - 1; i >= 0; i--) {
@@ -1453,6 +1455,7 @@ var SceneManager = (function () {
SceneManager._scene.begin(); SceneManager._scene.begin();
} }
} }
SceneManager.endDebugUpdate();
SceneManager.render(); SceneManager.render();
}; };
SceneManager.render = function () { SceneManager.render = function () {
@@ -1493,6 +1496,13 @@ var SceneManager = (function () {
SceneManager.emitter.emit(CoreEvents.SceneChanged); SceneManager.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged(); Time.sceneChanged();
}; };
SceneManager.startDebugUpdate = function () {
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
};
SceneManager.endDebugUpdate = function () {
TimeRuler.Instance.endMark("update");
};
return SceneManager; return SceneManager;
}()); }());
var Camera = (function (_super) { var Camera = (function (_super) {
@@ -1866,8 +1876,12 @@ var SpriteRenderer = (function (_super) {
return this.isVisible; return this.isVisible;
}; };
SpriteRenderer.prototype.render = function (camera) { SpriteRenderer.prototype.render = function (camera) {
if (this.x != -camera.position.x + camera.origin.x ||
this.y != -camera.position.y + camera.origin.y) {
this.x = -camera.position.x + camera.origin.x; this.x = -camera.position.x + camera.origin.x;
this.y = -camera.position.y + camera.origin.y; this.y = -camera.position.y + camera.origin.y;
this.entity.onEntityTransformChanged(TransformComponent.position);
}
}; };
SpriteRenderer.prototype.onRemovedFromEntity = function () { SpriteRenderer.prototype.onRemovedFromEntity = function () {
if (this.parent) if (this.parent)
@@ -2192,35 +2206,17 @@ var Collider = (function (_super) {
_this.registeredPhysicsBounds = new Rectangle(); _this.registeredPhysicsBounds = new Rectangle();
_this.shouldColliderScaleAndRotateWithTransform = true; _this.shouldColliderScaleAndRotateWithTransform = true;
_this.collidesWithLayers = Physics.allLayers; _this.collidesWithLayers = Physics.allLayers;
_this._localOffset = new Vector2(0, 0);
return _this; return _this;
} }
Object.defineProperty(Collider.prototype, "bounds", { Object.defineProperty(Collider.prototype, "bounds", {
get: function () { get: function () {
this.shape.recalculateBounds(this); var shapeBounds = this.shape.bounds;
return this.shape.bounds; var colliderBuonds = new Rectangle(this.entity.x, this.entity.y, shapeBounds.width, shapeBounds.height);
return colliderBuonds;
}, },
enumerable: true, enumerable: true,
configurable: true configurable: true
}); });
Object.defineProperty(Collider.prototype, "localOffset", {
get: function () {
return this._localOffset;
},
set: function (value) {
this.setLocalOffset(value);
},
enumerable: true,
configurable: true
});
Collider.prototype.setLocalOffset = function (offset) {
if (this._localOffset != offset) {
this.unregisterColliderWithPhysicsSystem();
this._localOffset = offset;
this._localOffsetLength = this._localOffset.length();
this.registerColliderWithPhysicsSystem();
}
};
Collider.prototype.registerColliderWithPhysicsSystem = function () { Collider.prototype.registerColliderWithPhysicsSystem = function () {
if (this._isParentEntityAddedToScene && !this._isColliderRegistered) { if (this._isParentEntityAddedToScene && !this._isColliderRegistered) {
Physics.addCollider(this); Physics.addCollider(this);
@@ -2237,12 +2233,12 @@ var Collider = (function (_super) {
return this.shape.overlaps(other.shape); return this.shape.overlaps(other.shape);
}; };
Collider.prototype.collidesWith = function (collider, motion) { Collider.prototype.collidesWith = function (collider, motion) {
var oldPosition = this.shape.position; var oldPosition = this.entity.position;
this.shape.position = Vector2.add(this.shape.position, motion); this.entity.position = Vector2.add(this.entity.position, motion);
var result = this.shape.collidesWithShape(collider.shape); var result = this.shape.collidesWithShape(collider.shape);
if (result) if (result)
result.collider = collider; result.collider = collider;
this.shape.position = oldPosition; this.entity.position = oldPosition;
return result; return result;
}; };
Collider.prototype.onAddedToEntity = function () { Collider.prototype.onAddedToEntity = function () {
@@ -2258,14 +2254,12 @@ var Collider = (function (_super) {
if (this instanceof CircleCollider) { if (this instanceof CircleCollider) {
var circleCollider = this; var circleCollider = this;
circleCollider.radius = Math.max(width, height) * 0.5; circleCollider.radius = Math.max(width, height) * 0.5;
this.localOffset = bounds.location;
} }
else { else {
var boxCollider = this; this.width = width;
boxCollider.width = width; this.height = height;
boxCollider.height = height;
this.localOffset = bounds.location;
} }
this.addChild(this.shape);
} }
else { else {
console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it."); console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it.");
@@ -2277,6 +2271,7 @@ var Collider = (function (_super) {
Collider.prototype.onRemovedFromEntity = function () { Collider.prototype.onRemovedFromEntity = function () {
this.unregisterColliderWithPhysicsSystem(); this.unregisterColliderWithPhysicsSystem();
this._isParentEntityAddedToScene = false; this._isParentEntityAddedToScene = false;
this.removeChild(this.shape);
}; };
Collider.prototype.onEnabled = function () { Collider.prototype.onEnabled = function () {
this.registerColliderWithPhysicsSystem(); this.registerColliderWithPhysicsSystem();
@@ -2291,8 +2286,8 @@ var Collider = (function (_super) {
Collider.prototype.update = function () { Collider.prototype.update = function () {
var renderable = this.entity.getComponent(RenderableComponent); var renderable = this.entity.getComponent(RenderableComponent);
if (renderable) { if (renderable) {
this.$setX(renderable.x + this.localOffset.x); this.$setX(renderable.x);
this.$setY(renderable.y + this.localOffset.y); this.$setY(renderable.y);
} }
}; };
return Collider; return Collider;
@@ -2395,8 +2390,6 @@ var PolygonCollider = (function (_super) {
var isPolygonClosed = points[0] == points[points.length - 1]; var isPolygonClosed = points[0] == points[points.length - 1];
if (isPolygonClosed) if (isPolygonClosed)
points.splice(points.length - 1, 1); points.splice(points.length - 1, 1);
var center = Polygon.findPolygonCenter(points);
_this.setLocalOffset(center);
Polygon.recenterPolygonVerts(points); Polygon.recenterPolygonVerts(points);
_this.shape = new Polygon(points); _this.shape = new Polygon(points);
return _this; return _this;
@@ -4402,6 +4395,13 @@ var Rectangle = (function (_super) {
} }
return boundsPoint; return boundsPoint;
}; };
Rectangle.prototype.setEgretRect = function (rect) {
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
return this;
};
Rectangle.rectEncompassingPoints = function (points) { Rectangle.rectEncompassingPoints = function (points) {
var minX = Number.POSITIVE_INFINITY; var minX = Number.POSITIVE_INFINITY;
var minY = Number.POSITIVE_INFINITY; var minY = Number.POSITIVE_INFINITY;
@@ -4687,24 +4687,37 @@ var Physics = (function () {
Physics.allLayers = -1; Physics.allLayers = -1;
return Physics; return Physics;
}()); }());
var Shape = (function () { var Shape = (function (_super) {
__extends(Shape, _super);
function Shape() { function Shape() {
this.bounds = new Rectangle(); return _super !== null && _super.apply(this, arguments) || this;
this.position = Vector2.zero;
} }
return Shape; return Shape;
}()); }(egret.DisplayObject));
var Polygon = (function (_super) { var Polygon = (function (_super) {
__extends(Polygon, _super); __extends(Polygon, _super);
function Polygon(points, isBox) { function Polygon(points, isBox) {
var _this = _super.call(this) || this; var _this = _super.call(this) || this;
_this.isUnrotated = true;
_this._areEdgeNormalsDirty = true; _this._areEdgeNormalsDirty = true;
_this.center = new Vector2(); _this.center = new Vector2();
_this.setPoints(points); _this.setPoints(points);
_this.isBox = isBox; _this.isBox = isBox;
return _this; return _this;
} }
Object.defineProperty(Polygon.prototype, "position", {
get: function () {
return new Vector2(this.parent.x, this.parent.y);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Polygon.prototype, "bounds", {
get: function () {
return new Rectangle(this.x, this.y, this.width, this.height);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Polygon.prototype, "edgeNormals", { Object.defineProperty(Polygon.prototype, "edgeNormals", {
get: function () { get: function () {
if (this._areEdgeNormalsDirty) if (this._areEdgeNormalsDirty)
@@ -4829,36 +4842,6 @@ var Polygon = (function (_super) {
} }
return verts; return verts;
}; };
Polygon.prototype.recalculateBounds = function (collider) {
var localOffset = collider.localOffset;
if (collider.shouldColliderScaleAndRotateWithTransform) {
var hasUnitScale = true;
var tempMat = void 0;
var combinedMatrix = Matrix2D.createTranslation(-this._polygonCenter.x, -this._polygonCenter.y);
if (collider.entity.scale != Vector2.one) {
tempMat = Matrix2D.createScale(collider.entity.scale.x, collider.entity.scale.y);
combinedMatrix = Matrix2D.multiply(combinedMatrix, tempMat);
hasUnitScale = false;
var scaledOffset = Vector2.multiply(collider.localOffset, collider.entity.scale);
localOffset = scaledOffset;
}
if (collider.entity.rotation != 0) {
tempMat = Matrix2D.createRotation(collider.entity.rotation, tempMat);
combinedMatrix = Matrix2D.multiply(combinedMatrix, tempMat);
var offsetAngle = Math.atan2(collider.localOffset.y, collider.localOffset.x) * MathHelper.Rad2Deg;
var offsetLength = hasUnitScale ? collider._localOffsetLength : (Vector2.multiply(collider.localOffset, collider.entity.scale)).length();
localOffset = MathHelper.pointOnCirlce(Vector2.zero, offsetLength, MathHelper.toDegrees(collider.entity.rotation) + offsetAngle);
}
tempMat = Matrix2D.createTranslation(this._polygonCenter.x, this._polygonCenter.y);
combinedMatrix = Matrix2D.multiply(combinedMatrix, tempMat);
Vector2Ext.transform(this._originalPoints, combinedMatrix, this.points);
this.isUnrotated = collider.entity.rotation == 0;
}
this.position = Vector2.add(collider.entity.position, localOffset);
this.bounds = Rectangle.rectEncompassingPoints(this.points);
this.bounds.location = Vector2.add(this.bounds.location, this.position);
this.center = localOffset;
};
return Polygon; return Polygon;
}(Shape)); }(Shape));
var Box = (function (_super) { var Box = (function (_super) {
@@ -4880,16 +4863,14 @@ var Box = (function (_super) {
return verts; return verts;
}; };
Box.prototype.overlaps = function (other) { Box.prototype.overlaps = function (other) {
if (this.isUnrotated) { if (other instanceof Box)
if (other instanceof Box && other.isUnrotated)
return this.bounds.intersects(other.bounds); return this.bounds.intersects(other.bounds);
if (other instanceof Circle) if (other instanceof Circle)
return Collisions.isRectToCircle(this.bounds, other.position, other.radius); return Collisions.isRectToCircle(this.bounds, other.position, other.radius);
}
return _super.prototype.overlaps.call(this, other); return _super.prototype.overlaps.call(this, other);
}; };
Box.prototype.collidesWithShape = function (other) { Box.prototype.collidesWithShape = function (other) {
if (this.isUnrotated && other instanceof Box && other.isUnrotated) { if (other instanceof Box) {
return ShapeCollisions.boxToBox(this, other); return ShapeCollisions.boxToBox(this, other);
} }
return _super.prototype.collidesWithShape.call(this, other); return _super.prototype.collidesWithShape.call(this, other);
@@ -4907,9 +4888,7 @@ var Box = (function (_super) {
this._originalPoints[i] = this.points[i]; this._originalPoints[i] = this.points[i];
}; };
Box.prototype.containsPoint = function (point) { Box.prototype.containsPoint = function (point) {
if (this.isUnrotated)
return this.bounds.contains(point.x, point.y); return this.bounds.contains(point.x, point.y);
return _super.prototype.containsPoint.call(this, point);
}; };
return Box; return Box;
}(Polygon)); }(Polygon));
@@ -4922,11 +4901,25 @@ var Circle = (function (_super) {
_this._originalRadius = radius; _this._originalRadius = radius;
return _this; return _this;
} }
Object.defineProperty(Circle.prototype, "position", {
get: function () {
return new Vector2(this.parent.x, this.parent.y);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "bounds", {
get: function () {
return new Rectangle().setEgretRect(this.getBounds());
},
enumerable: true,
configurable: true
});
Circle.prototype.pointCollidesWithShape = function (point) { Circle.prototype.pointCollidesWithShape = function (point) {
return ShapeCollisions.pointToCircle(point, this); return ShapeCollisions.pointToCircle(point, this);
}; };
Circle.prototype.collidesWithShape = function (other) { Circle.prototype.collidesWithShape = function (other) {
if (other instanceof Box && other.isUnrotated) { if (other instanceof Box) {
return ShapeCollisions.circleToBox(this, other); return ShapeCollisions.circleToBox(this, other);
} }
if (other instanceof Circle) { if (other instanceof Circle) {
@@ -4937,24 +4930,8 @@ var Circle = (function (_super) {
} }
throw new Error("Collisions of Circle to " + other + " are not supported"); throw new Error("Collisions of Circle to " + other + " are not supported");
}; };
Circle.prototype.recalculateBounds = function (collider) {
this.center = collider.localOffset;
if (collider.shouldColliderScaleAndRotateWithTransform) {
var scale = collider.entity.scale;
var hasUnitScale = scale.x == 1 && scale.y == 1;
var maxScale = Math.max(scale.x, scale.y);
this.radius = this._originalRadius * maxScale;
if (collider.entity.rotation != 0) {
var offsetAngle = Math.atan2(collider.localOffset.y, collider.localOffset.x) * MathHelper.Rad2Deg;
var offsetLength = hasUnitScale ? collider._localOffsetLength : (Vector2.multiply(collider.localOffset, collider.entity.scale)).length();
this.center = MathHelper.pointOnCirlce(Vector2.zero, offsetLength, MathHelper.toDegrees(collider.entity.rotation) + offsetAngle);
}
}
this.position = Vector2.add(collider.entity.position, this.center);
this.bounds = new Rectangle(this.position.x - this.radius, this.position.y - this.radius, this.radius * 2, this.radius * 2);
};
Circle.prototype.overlaps = function (other) { Circle.prototype.overlaps = function (other) {
if (other instanceof Box && other.isUnrotated) if (other instanceof Box)
return Collisions.isRectToCircle(other.bounds, this.position, this.radius); return Collisions.isRectToCircle(other.bounds, this.position, this.radius);
if (other instanceof Circle) if (other instanceof Circle)
return Collisions.isCircleToCircle(this.position, this.radius, other.position, other.radius); return Collisions.isCircleToCircle(this.position, this.radius, other.position, other.radius);
@@ -5203,6 +5180,7 @@ var SpatialHash = (function () {
for (var x = p1.x; x <= p2.x; x++) { for (var x = p1.x; x <= p2.x; x++) {
for (var y = p1.y; y <= p2.y; y++) { for (var y = p1.y; y <= p2.y; y++) {
var c = this.cellAtPosition(x, y, true); var c = this.cellAtPosition(x, y, true);
if (c.indexOf(collider) == -1)
c.push(collider); c.push(collider);
} }
} }
@@ -5213,7 +5191,6 @@ var SpatialHash = (function () {
SpatialHash.prototype.overlapCircle = function (circleCenter, radius, results, layerMask) { SpatialHash.prototype.overlapCircle = function (circleCenter, radius, results, layerMask) {
var bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2); var bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2);
this._overlapTestCircle.radius = radius; this._overlapTestCircle.radius = radius;
this._overlapTestCircle.position = circleCenter;
var resultCounter = 0; var resultCounter = 0;
var aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask); var aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask);
bounds = aabbBroadphaseResult.bounds; bounds = aabbBroadphaseResult.bounds;
@@ -5306,13 +5283,7 @@ var NumberDictionary = (function () {
this._store = new Map(); this._store = new Map();
} }
NumberDictionary.prototype.getKey = function (x, y) { NumberDictionary.prototype.getKey = function (x, y) {
return Long.fromNumber(x).shiftLeft(32).or(this.intToUint(y)).toString(); return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, false)).toString();
};
NumberDictionary.prototype.intToUint = function (i) {
if (i >= 0)
return i;
else
return 4294967296 + i;
}; };
NumberDictionary.prototype.add = function (x, y, list) { NumberDictionary.prototype.add = function (x, y, list) {
this._store.set(this.getKey(x, y), list); this._store.set(this.getKey(x, y), list);
@@ -6296,8 +6267,12 @@ var RectangleExt = (function () {
} }
RectangleExt.union = function (first, point) { RectangleExt.union = function (first, point) {
var rect = new Rectangle(point.x, point.y, 0, 0); var rect = new Rectangle(point.x, point.y, 0, 0);
var rectResult = first.union(rect); var result = new Rectangle();
return new Rectangle(rectResult.x, rectResult.y, rectResult.width, rectResult.height); result.x = Math.min(first.x, rect.x);
result.y = Math.min(first.y, rect.y);
result.width = Math.max(first.right, rect.right) - result.x;
result.height = Math.max(first.bottom, result.bottom) - result.y;
return result;
}; };
return RectangleExt; return RectangleExt;
}()); }());
@@ -6648,6 +6623,8 @@ var TimeRuler = (function () {
var lock = new LockUtils(this._frameKey); var lock = new LockUtils(this._frameKey);
lock.lock().then(function () { lock.lock().then(function () {
_this._updateCount = parseInt(egret.localStorage.getItem(_this._frameKey), 10); _this._updateCount = parseInt(egret.localStorage.getItem(_this._frameKey), 10);
if (isNaN(_this._updateCount))
_this._updateCount = 0;
var count = _this._updateCount; var count = _this._updateCount;
count += 1; count += 1;
egret.localStorage.setItem(_this._frameKey, count.toString()); egret.localStorage.setItem(_this._frameKey, count.toString());
@@ -6714,7 +6691,7 @@ var TimeRuler = (function () {
throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls"); throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");
} }
var markerId = _this._markerNameToIdMap.get(markerName); var markerId = _this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
markerId = _this.markers.length; markerId = _this.markers.length;
_this._markerNameToIdMap.set(markerName, markerId); _this._markerNameToIdMap.set(markerName, markerId);
} }
@@ -6737,7 +6714,7 @@ var TimeRuler = (function () {
throw new Error("call beginMark method before calling endMark method"); throw new Error("call beginMark method before calling endMark method");
} }
var markerId = _this._markerNameToIdMap.get(markerName); var markerId = _this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
throw new Error("Marker " + markerName + " is not registered. Make sure you specifed same name as you used for beginMark method"); throw new Error("Marker " + markerName + " is not registered. Make sure you specifed same name as you used for beginMark method");
} }
var markerIdx = bar.markerNests[--bar.nestCount]; var markerIdx = bar.markerNests[--bar.nestCount];
@@ -6810,7 +6787,7 @@ var TimeRuler = (function () {
var startY = position.y - (height - TimeRuler.barHeight); var startY = position.y - (height - TimeRuler.barHeight);
var y = startY; var y = startY;
}; };
TimeRuler.maxBars = 0; TimeRuler.maxBars = 8;
TimeRuler.maxSamples = 256; TimeRuler.maxSamples = 256;
TimeRuler.maxNestCall = 32; TimeRuler.maxNestCall = 32;
TimeRuler.barHeight = 8; TimeRuler.barHeight = 8;
@@ -6823,20 +6800,27 @@ var TimeRuler = (function () {
var FrameLog = (function () { var FrameLog = (function () {
function FrameLog() { function FrameLog() {
this.bars = new Array(TimeRuler.maxBars); this.bars = new Array(TimeRuler.maxBars);
for (var i = 0; i < TimeRuler.maxBars; ++i) this.bars.fill(new MarkerCollection(), 0, TimeRuler.maxBars);
this.bars[i] = new MarkerCollection();
} }
return FrameLog; return FrameLog;
}()); }());
var MarkerCollection = (function () { var MarkerCollection = (function () {
function MarkerCollection() { function MarkerCollection() {
this.markers = new Array(TimeRuler.maxSamples); this.markers = new Array(TimeRuler.maxSamples);
this.markCount = 0;
this.markerNests = new Array(TimeRuler.maxNestCall); this.markerNests = new Array(TimeRuler.maxNestCall);
this.nestCount = 0;
this.markers.fill(new Marker(), 0, TimeRuler.maxSamples);
this.markerNests.fill(0, 0, TimeRuler.maxNestCall);
} }
return MarkerCollection; return MarkerCollection;
}()); }());
var Marker = (function () { var Marker = (function () {
function Marker() { function Marker() {
this.markerId = 0;
this.beginTime = 0;
this.endTime = 0;
this.color = 0x000000;
} }
return Marker; return Marker;
}()); }());
@@ -6844,11 +6828,21 @@ var MarkerInfo = (function () {
function MarkerInfo(name) { function MarkerInfo(name) {
this.logs = new Array(TimeRuler.maxBars); this.logs = new Array(TimeRuler.maxBars);
this.name = name; this.name = name;
this.logs.fill(new MarkerLog(), 0, TimeRuler.maxBars);
} }
return MarkerInfo; return MarkerInfo;
}()); }());
var MarkerLog = (function () { var MarkerLog = (function () {
function MarkerLog() { function MarkerLog() {
this.snapMin = 0;
this.snapMax = 0;
this.snapAvg = 0;
this.min = 0;
this.max = 0;
this.avg = 0;
this.samples = 0;
this.color = 0x000000;
this.initialized = false;
} }
return MarkerLog; return MarkerLog;
}()); }());
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -18,11 +18,11 @@ class MainScene extends Scene {
bg.addComponent(new BoxCollider()); bg.addComponent(new BoxCollider());
bg.position = new Vector2(Math.random() * 200, Math.random() * 200); bg.position = new Vector2(Math.random() * 200, Math.random() * 200);
for (let i = 0; i < 20; i++) { for (let i = 0; i < 1; i++) {
let sprite = new Sprite(RES.getRes("checkbox_select_disabled_png")); let sprite = new Sprite(RES.getRes("checkbox_select_disabled_png"));
let player2 = this.createEntity("player2"); let player2 = this.createEntity("player2");
player2.addComponent(new SpriteRenderer()).setSprite(sprite); player2.addComponent(new SpriteRenderer()).setSprite(sprite);
player2.position = new Vector2(Math.random() * 1000, Math.random() * 1000); player2.position = new Vector2(Math.random() * 100, Math.random() * 100);
player2.addComponent(new BoxCollider()); player2.addComponent(new BoxCollider());
} }
+8 -6
View File
@@ -245,7 +245,7 @@ declare class Entity extends egret.DisplayObjectContainer {
getOrCreateComponent<T extends Component>(type: T): T; getOrCreateComponent<T extends Component>(type: T): T;
getComponent<T extends Component>(type: any): T; getComponent<T extends Component>(type: any): T;
getComponents(typeName: string | any, componentList?: any): any; getComponents(typeName: string | any, componentList?: any): any;
private onEntityTransformChanged; onEntityTransformChanged(comp: TransformComponent): void;
removeComponentForType<T extends Component>(type: any): boolean; removeComponentForType<T extends Component>(type: any): boolean;
removeComponent(component: Component): void; removeComponent(component: Component): void;
removeAllComponents(): void; removeAllComponents(): void;
@@ -300,6 +300,7 @@ declare class SceneManager {
static emitter: Emitter<CoreEvents>; static emitter: Emitter<CoreEvents>;
static content: ContentManager; static content: ContentManager;
private static _instnace; private static _instnace;
private static timerRuler;
static readonly Instance: SceneManager; static readonly Instance: SceneManager;
constructor(stage: egret.Stage); constructor(stage: egret.Stage);
static scene: Scene; static scene: Scene;
@@ -309,6 +310,8 @@ declare class SceneManager {
static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T; static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T;
static registerActiveSceneChanged(current: Scene, next: Scene): void; static registerActiveSceneChanged(current: Scene, next: Scene): void;
onSceneChanged(): void; onSceneChanged(): void;
private static startDebugUpdate;
private static endDebugUpdate;
} }
declare class Camera extends Component { declare class Camera extends Component {
private _zoom; private _zoom;
@@ -488,14 +491,10 @@ declare abstract class Collider extends Component {
registeredPhysicsBounds: Rectangle; registeredPhysicsBounds: Rectangle;
shouldColliderScaleAndRotateWithTransform: boolean; shouldColliderScaleAndRotateWithTransform: boolean;
collidesWithLayers: number; collidesWithLayers: number;
_localOffsetLength: number;
protected _isParentEntityAddedToScene: any; protected _isParentEntityAddedToScene: any;
protected _colliderRequiresAutoSizing: any; protected _colliderRequiresAutoSizing: any;
protected _localOffset: Vector2;
protected _isColliderRegistered: any; protected _isColliderRegistered: any;
readonly bounds: Rectangle; readonly bounds: Rectangle;
localOffset: Vector2;
setLocalOffset(offset: Vector2): void;
registerColliderWithPhysicsSystem(): void; registerColliderWithPhysicsSystem(): void;
unregisterColliderWithPhysicsSystem(): void; unregisterColliderWithPhysicsSystem(): void;
overlaps(other: Collider): any; overlaps(other: Collider): any;
@@ -958,8 +957,8 @@ declare class Physics {
} }
declare abstract class Shape extends egret.DisplayObject { declare abstract class Shape extends egret.DisplayObject {
abstract bounds: Rectangle; abstract bounds: Rectangle;
position: Vector2;
abstract center: Vector2; abstract center: Vector2;
abstract position: Vector2;
abstract pointCollidesWithShape(point: Vector2): CollisionResult; abstract pointCollidesWithShape(point: Vector2): CollisionResult;
abstract overlaps(other: Shape): any; abstract overlaps(other: Shape): any;
abstract collidesWithShape(other: Shape): CollisionResult; abstract collidesWithShape(other: Shape): CollisionResult;
@@ -970,6 +969,7 @@ declare class Polygon extends Shape {
private _areEdgeNormalsDirty; private _areEdgeNormalsDirty;
protected _originalPoints: Vector2[]; protected _originalPoints: Vector2[];
center: Vector2; center: Vector2;
readonly position: Vector2;
readonly bounds: Rectangle; readonly bounds: Rectangle;
_edgeNormals: Vector2[]; _edgeNormals: Vector2[];
readonly edgeNormals: Vector2[]; readonly edgeNormals: Vector2[];
@@ -1003,6 +1003,7 @@ declare class Circle extends Shape {
radius: number; radius: number;
_originalRadius: number; _originalRadius: number;
center: Vector2; center: Vector2;
readonly position: Vector2;
readonly bounds: Rectangle; readonly bounds: Rectangle;
constructor(radius: number); constructor(radius: number);
pointCollidesWithShape(point: Vector2): CollisionResult; pointCollidesWithShape(point: Vector2): CollisionResult;
@@ -1409,6 +1410,7 @@ declare class MarkerCollection {
markCount: number; markCount: number;
markerNests: number[]; markerNests: number[];
nestCount: number; nestCount: number;
constructor();
} }
declare class Marker { declare class Marker {
markerId: number; markerId: number;
+63 -39
View File
@@ -1403,6 +1403,7 @@ var SceneManager = (function () {
SceneManager.content = new ContentManager(); SceneManager.content = new ContentManager();
SceneManager.stage = stage; SceneManager.stage = stage;
SceneManager.initialize(stage); SceneManager.initialize(stage);
SceneManager.timerRuler = new TimeRuler();
} }
Object.defineProperty(SceneManager, "Instance", { Object.defineProperty(SceneManager, "Instance", {
get: function () { get: function () {
@@ -1435,6 +1436,7 @@ var SceneManager = (function () {
Input.initialize(stage); Input.initialize(stage);
}; };
SceneManager.update = function () { SceneManager.update = function () {
SceneManager.startDebugUpdate();
Time.update(egret.getTimer()); Time.update(egret.getTimer());
if (SceneManager._scene) { if (SceneManager._scene) {
for (var i = GlobalManager.globalManagers.length - 1; i >= 0; i--) { for (var i = GlobalManager.globalManagers.length - 1; i >= 0; i--) {
@@ -1453,6 +1455,7 @@ var SceneManager = (function () {
SceneManager._scene.begin(); SceneManager._scene.begin();
} }
} }
SceneManager.endDebugUpdate();
SceneManager.render(); SceneManager.render();
}; };
SceneManager.render = function () { SceneManager.render = function () {
@@ -1493,6 +1496,13 @@ var SceneManager = (function () {
SceneManager.emitter.emit(CoreEvents.SceneChanged); SceneManager.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged(); Time.sceneChanged();
}; };
SceneManager.startDebugUpdate = function () {
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
};
SceneManager.endDebugUpdate = function () {
TimeRuler.Instance.endMark("update");
};
return SceneManager; return SceneManager;
}()); }());
var Camera = (function (_super) { var Camera = (function (_super) {
@@ -1866,8 +1876,12 @@ var SpriteRenderer = (function (_super) {
return this.isVisible; return this.isVisible;
}; };
SpriteRenderer.prototype.render = function (camera) { SpriteRenderer.prototype.render = function (camera) {
if (this.x != -camera.position.x + camera.origin.x ||
this.y != -camera.position.y + camera.origin.y) {
this.x = -camera.position.x + camera.origin.x; this.x = -camera.position.x + camera.origin.x;
this.y = -camera.position.y + camera.origin.y; this.y = -camera.position.y + camera.origin.y;
this.entity.onEntityTransformChanged(TransformComponent.position);
}
}; };
SpriteRenderer.prototype.onRemovedFromEntity = function () { SpriteRenderer.prototype.onRemovedFromEntity = function () {
if (this.parent) if (this.parent)
@@ -2192,36 +2206,17 @@ var Collider = (function (_super) {
_this.registeredPhysicsBounds = new Rectangle(); _this.registeredPhysicsBounds = new Rectangle();
_this.shouldColliderScaleAndRotateWithTransform = true; _this.shouldColliderScaleAndRotateWithTransform = true;
_this.collidesWithLayers = Physics.allLayers; _this.collidesWithLayers = Physics.allLayers;
_this._localOffset = new Vector2(0, 0);
return _this; return _this;
} }
Object.defineProperty(Collider.prototype, "bounds", { Object.defineProperty(Collider.prototype, "bounds", {
get: function () { get: function () {
var shapeBounds = this.shape.bounds; var shapeBounds = this.shape.bounds;
var colliderBuonds = new Rectangle(this.x + this.localOffset.x, this.y + this.localOffset.y, shapeBounds.width, shapeBounds.height); var colliderBuonds = new Rectangle(this.entity.x, this.entity.y, shapeBounds.width, shapeBounds.height);
return colliderBuonds; return colliderBuonds;
}, },
enumerable: true, enumerable: true,
configurable: true configurable: true
}); });
Object.defineProperty(Collider.prototype, "localOffset", {
get: function () {
return this._localOffset;
},
set: function (value) {
this.setLocalOffset(value);
},
enumerable: true,
configurable: true
});
Collider.prototype.setLocalOffset = function (offset) {
if (this._localOffset != offset) {
this.unregisterColliderWithPhysicsSystem();
this._localOffset = offset;
this._localOffsetLength = this._localOffset.length();
this.registerColliderWithPhysicsSystem();
}
};
Collider.prototype.registerColliderWithPhysicsSystem = function () { Collider.prototype.registerColliderWithPhysicsSystem = function () {
if (this._isParentEntityAddedToScene && !this._isColliderRegistered) { if (this._isParentEntityAddedToScene && !this._isColliderRegistered) {
Physics.addCollider(this); Physics.addCollider(this);
@@ -2238,12 +2233,12 @@ var Collider = (function (_super) {
return this.shape.overlaps(other.shape); return this.shape.overlaps(other.shape);
}; };
Collider.prototype.collidesWith = function (collider, motion) { Collider.prototype.collidesWith = function (collider, motion) {
var oldPosition = this.shape.position; var oldPosition = this.entity.position;
this.shape.position = Vector2.add(this.shape.position, motion); this.entity.position = Vector2.add(this.entity.position, motion);
var result = this.shape.collidesWithShape(collider.shape); var result = this.shape.collidesWithShape(collider.shape);
if (result) if (result)
result.collider = collider; result.collider = collider;
this.shape.position = oldPosition; this.entity.position = oldPosition;
return result; return result;
}; };
Collider.prototype.onAddedToEntity = function () { Collider.prototype.onAddedToEntity = function () {
@@ -2259,13 +2254,12 @@ var Collider = (function (_super) {
if (this instanceof CircleCollider) { if (this instanceof CircleCollider) {
var circleCollider = this; var circleCollider = this;
circleCollider.radius = Math.max(width, height) * 0.5; circleCollider.radius = Math.max(width, height) * 0.5;
this.localOffset = bounds.location;
} }
else { else {
this.width = width; this.width = width;
this.height = height; this.height = height;
this.localOffset = bounds.location;
} }
this.addChild(this.shape);
} }
else { else {
console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it."); console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it.");
@@ -2277,6 +2271,7 @@ var Collider = (function (_super) {
Collider.prototype.onRemovedFromEntity = function () { Collider.prototype.onRemovedFromEntity = function () {
this.unregisterColliderWithPhysicsSystem(); this.unregisterColliderWithPhysicsSystem();
this._isParentEntityAddedToScene = false; this._isParentEntityAddedToScene = false;
this.removeChild(this.shape);
}; };
Collider.prototype.onEnabled = function () { Collider.prototype.onEnabled = function () {
this.registerColliderWithPhysicsSystem(); this.registerColliderWithPhysicsSystem();
@@ -2291,8 +2286,8 @@ var Collider = (function (_super) {
Collider.prototype.update = function () { Collider.prototype.update = function () {
var renderable = this.entity.getComponent(RenderableComponent); var renderable = this.entity.getComponent(RenderableComponent);
if (renderable) { if (renderable) {
this.$setX(renderable.x + this.localOffset.x); this.$setX(renderable.x);
this.$setY(renderable.y + this.localOffset.y); this.$setY(renderable.y);
} }
}; };
return Collider; return Collider;
@@ -2395,8 +2390,6 @@ var PolygonCollider = (function (_super) {
var isPolygonClosed = points[0] == points[points.length - 1]; var isPolygonClosed = points[0] == points[points.length - 1];
if (isPolygonClosed) if (isPolygonClosed)
points.splice(points.length - 1, 1); points.splice(points.length - 1, 1);
var center = Polygon.findPolygonCenter(points);
_this.setLocalOffset(center);
Polygon.recenterPolygonVerts(points); Polygon.recenterPolygonVerts(points);
_this.shape = new Polygon(points); _this.shape = new Polygon(points);
return _this; return _this;
@@ -4697,9 +4690,7 @@ var Physics = (function () {
var Shape = (function (_super) { var Shape = (function (_super) {
__extends(Shape, _super); __extends(Shape, _super);
function Shape() { function Shape() {
var _this = _super !== null && _super.apply(this, arguments) || this; return _super !== null && _super.apply(this, arguments) || this;
_this.position = Vector2.zero;
return _this;
} }
return Shape; return Shape;
}(egret.DisplayObject)); }(egret.DisplayObject));
@@ -4713,9 +4704,16 @@ var Polygon = (function (_super) {
_this.isBox = isBox; _this.isBox = isBox;
return _this; return _this;
} }
Object.defineProperty(Polygon.prototype, "position", {
get: function () {
return new Vector2(this.parent.x, this.parent.y);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Polygon.prototype, "bounds", { Object.defineProperty(Polygon.prototype, "bounds", {
get: function () { get: function () {
return new Rectangle(0, 0, this.width, this.height); return new Rectangle(this.x, this.y, this.width, this.height);
}, },
enumerable: true, enumerable: true,
configurable: true configurable: true
@@ -4903,6 +4901,13 @@ var Circle = (function (_super) {
_this._originalRadius = radius; _this._originalRadius = radius;
return _this; return _this;
} }
Object.defineProperty(Circle.prototype, "position", {
get: function () {
return new Vector2(this.parent.x, this.parent.y);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "bounds", { Object.defineProperty(Circle.prototype, "bounds", {
get: function () { get: function () {
return new Rectangle().setEgretRect(this.getBounds()); return new Rectangle().setEgretRect(this.getBounds());
@@ -5175,6 +5180,7 @@ var SpatialHash = (function () {
for (var x = p1.x; x <= p2.x; x++) { for (var x = p1.x; x <= p2.x; x++) {
for (var y = p1.y; y <= p2.y; y++) { for (var y = p1.y; y <= p2.y; y++) {
var c = this.cellAtPosition(x, y, true); var c = this.cellAtPosition(x, y, true);
if (c.indexOf(collider) == -1)
c.push(collider); c.push(collider);
} }
} }
@@ -5185,7 +5191,6 @@ var SpatialHash = (function () {
SpatialHash.prototype.overlapCircle = function (circleCenter, radius, results, layerMask) { SpatialHash.prototype.overlapCircle = function (circleCenter, radius, results, layerMask) {
var bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2); var bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2);
this._overlapTestCircle.radius = radius; this._overlapTestCircle.radius = radius;
this._overlapTestCircle.position = circleCenter;
var resultCounter = 0; var resultCounter = 0;
var aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask); var aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask);
bounds = aabbBroadphaseResult.bounds; bounds = aabbBroadphaseResult.bounds;
@@ -6618,6 +6623,8 @@ var TimeRuler = (function () {
var lock = new LockUtils(this._frameKey); var lock = new LockUtils(this._frameKey);
lock.lock().then(function () { lock.lock().then(function () {
_this._updateCount = parseInt(egret.localStorage.getItem(_this._frameKey), 10); _this._updateCount = parseInt(egret.localStorage.getItem(_this._frameKey), 10);
if (isNaN(_this._updateCount))
_this._updateCount = 0;
var count = _this._updateCount; var count = _this._updateCount;
count += 1; count += 1;
egret.localStorage.setItem(_this._frameKey, count.toString()); egret.localStorage.setItem(_this._frameKey, count.toString());
@@ -6684,7 +6691,7 @@ var TimeRuler = (function () {
throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls"); throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");
} }
var markerId = _this._markerNameToIdMap.get(markerName); var markerId = _this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
markerId = _this.markers.length; markerId = _this.markers.length;
_this._markerNameToIdMap.set(markerName, markerId); _this._markerNameToIdMap.set(markerName, markerId);
} }
@@ -6707,7 +6714,7 @@ var TimeRuler = (function () {
throw new Error("call beginMark method before calling endMark method"); throw new Error("call beginMark method before calling endMark method");
} }
var markerId = _this._markerNameToIdMap.get(markerName); var markerId = _this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
throw new Error("Marker " + markerName + " is not registered. Make sure you specifed same name as you used for beginMark method"); throw new Error("Marker " + markerName + " is not registered. Make sure you specifed same name as you used for beginMark method");
} }
var markerIdx = bar.markerNests[--bar.nestCount]; var markerIdx = bar.markerNests[--bar.nestCount];
@@ -6780,7 +6787,7 @@ var TimeRuler = (function () {
var startY = position.y - (height - TimeRuler.barHeight); var startY = position.y - (height - TimeRuler.barHeight);
var y = startY; var y = startY;
}; };
TimeRuler.maxBars = 0; TimeRuler.maxBars = 8;
TimeRuler.maxSamples = 256; TimeRuler.maxSamples = 256;
TimeRuler.maxNestCall = 32; TimeRuler.maxNestCall = 32;
TimeRuler.barHeight = 8; TimeRuler.barHeight = 8;
@@ -6793,20 +6800,27 @@ var TimeRuler = (function () {
var FrameLog = (function () { var FrameLog = (function () {
function FrameLog() { function FrameLog() {
this.bars = new Array(TimeRuler.maxBars); this.bars = new Array(TimeRuler.maxBars);
for (var i = 0; i < TimeRuler.maxBars; ++i) this.bars.fill(new MarkerCollection(), 0, TimeRuler.maxBars);
this.bars[i] = new MarkerCollection();
} }
return FrameLog; return FrameLog;
}()); }());
var MarkerCollection = (function () { var MarkerCollection = (function () {
function MarkerCollection() { function MarkerCollection() {
this.markers = new Array(TimeRuler.maxSamples); this.markers = new Array(TimeRuler.maxSamples);
this.markCount = 0;
this.markerNests = new Array(TimeRuler.maxNestCall); this.markerNests = new Array(TimeRuler.maxNestCall);
this.nestCount = 0;
this.markers.fill(new Marker(), 0, TimeRuler.maxSamples);
this.markerNests.fill(0, 0, TimeRuler.maxNestCall);
} }
return MarkerCollection; return MarkerCollection;
}()); }());
var Marker = (function () { var Marker = (function () {
function Marker() { function Marker() {
this.markerId = 0;
this.beginTime = 0;
this.endTime = 0;
this.color = 0x000000;
} }
return Marker; return Marker;
}()); }());
@@ -6814,11 +6828,21 @@ var MarkerInfo = (function () {
function MarkerInfo(name) { function MarkerInfo(name) {
this.logs = new Array(TimeRuler.maxBars); this.logs = new Array(TimeRuler.maxBars);
this.name = name; this.name = name;
this.logs.fill(new MarkerLog(), 0, TimeRuler.maxBars);
} }
return MarkerInfo; return MarkerInfo;
}()); }());
var MarkerLog = (function () { var MarkerLog = (function () {
function MarkerLog() { function MarkerLog() {
this.snapMin = 0;
this.snapMax = 0;
this.snapAvg = 0;
this.min = 0;
this.max = 0;
this.avg = 0;
this.samples = 0;
this.color = 0x000000;
this.initialized = false;
} }
return MarkerLog; return MarkerLog;
}()); }());
+1 -1
View File
File diff suppressed because one or more lines are too long
+98 -57
View File
@@ -1,21 +1,105 @@
abstract class Component extends egret.DisplayObjectContainer { module es {
/**
*
* - onAddedToEntity
* - OnEnabled
*
*
* - onRemovedFromEntity
*/
export abstract class Component {
/**
*
*/
public entity: Entity; public entity: Entity;
private _enabled: boolean = true;
public updateInterval: number = 1;
/** 允许用户为实体存入信息 */
public userData: any;
private _updateOrder = 0;
/**
* 访 this.entity.transform
*/
public get transform(): Transform {
return this.entity.transform;
}
/**
* onEnabled/onDisable
*/
public get enabled() { public get enabled() {
return this.entity ? this.entity.enabled && this._enabled : this._enabled; return this.entity ? this.entity.enabled && this._enabled : this._enabled;
} }
/**
* onEnabled/onDisable
* @param value
*/
public set enabled(value: boolean) { public set enabled(value: boolean) {
this.setEnabled(value); this.setEnabled(value);
} }
public get localPosition(){ /** 更新此实体上组件的顺序 */
return new Vector2(this.entity.x + this.x, this.entity.y + this.y); public get updateOrder() {
return this._updateOrder;
}
/** 更新此实体上组件的顺序 */
public set updateOrder(value: number) {
this.setUpdateOrder(value);
}
/**
*
*/
public updateInterval: number = 1;
private _enabled: boolean = true;
private _updateOrder = 0;
/**
* 西访
*/
public initialize() {
}
/**
*
*/
public onAddedToEntity() {
}
/**
*
*/
public onRemovedFromEntity() {
}
/**
*
* @param comp
*/
public onEntityTransformChanged(comp: Transform.Component) {
}
/**
*
*/
public debugRender() {
}
/**
*
*/
public onEnabled() {
}
/**
*
*/
public onDisabled() {
}
/**
*
*/
public update() {
} }
public setEnabled(isEnabled: boolean) { public setEnabled(isEnabled: boolean) {
@@ -32,14 +116,6 @@ abstract class Component extends egret.DisplayObjectContainer {
return this; return this;
} }
/** 更新此实体上组件的顺序 */
public get updateOrder(){
return this._updateOrder;
}
/** 更新此实体上组件的顺序 */
public set updateOrder(value: number){
this.setUpdateOrder(value);
}
public setUpdateOrder(updateOrder: number) { public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) { if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder; this._updateOrder = updateOrder;
@@ -48,49 +124,14 @@ abstract class Component extends egret.DisplayObjectContainer {
return this; return this;
} }
public initialize(){
}
public onAddedToEntity(){
}
public onRemovedFromEntity(){
}
public onEnabled(){
}
public onDisabled(){
}
public debugRender(){
}
public update(){
}
/** /**
* *
* @param comp
*/ */
public onEntityTransformChanged(comp: TransformComponent){ public clone(): Component {
let component = ObjectUtils.clone<Component>(this);
component.entity = null;
} return component;
}
/** 内部使用 运行时不应该调用 */
public registerComponent(){
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this), false);
this.entity.scene.entityProcessors.onComponentAdded(this.entity);
}
public deregisterComponent(){
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this));
this.entity.scene.entityProcessors.onComponentRemoved(this.entity);
} }
} }
+4 -2
View File
@@ -1,4 +1,5 @@
class Camera extends Component { module es {
export class Camera extends Component {
private _zoom; private _zoom;
private _origin: Vector2 = Vector2.zero; private _origin: Vector2 = Vector2.zero;
@@ -228,7 +229,8 @@ class Camera extends Component {
} }
} }
enum CameraStyle { export enum CameraStyle {
lockOn, lockOn,
cameraWindow, cameraWindow,
} }
}
@@ -1,6 +1,14 @@
abstract class Collider extends Component { abstract class Collider extends Component {
/** 对撞机的基本形状 */ /** 对撞机的基本形状 */
public shape: Shape; public shape: Shape;
protected _localOffset: Vector2 = Vector2.zero;
public get localOffset(){
return this._localOffset;
}
public set localOffset(){
}
public _localOffsetLength: number;
/** 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法。 */ /** 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法。 */
public physicsLayer = 1 << 0; public physicsLayer = 1 << 0;
/** 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 */ /** 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 */
@@ -15,38 +23,32 @@ abstract class Collider extends Component {
/** 默认为所有层。 */ /** 默认为所有层。 */
public collidesWithLayers = Physics.allLayers; public collidesWithLayers = Physics.allLayers;
public _localOffsetLength: number;
/** 标记来跟踪我们的实体是否被添加到场景中 */ /** 标记来跟踪我们的实体是否被添加到场景中 */
protected _isParentEntityAddedToScene; protected _isParentEntityAddedToScene;
protected _colliderRequiresAutoSizing; protected _colliderRequiresAutoSizing;
protected _localOffset: Vector2 = new Vector2(0, 0);
/** 标记来记录我们是否注册了物理系统 */ /** 标记来记录我们是否注册了物理系统 */
protected _isColliderRegistered; protected _isColliderRegistered;
public get bounds(): Rectangle { public get bounds(): Rectangle {
let shapeBounds = this.shape.bounds; let shapeBounds = this.shape.bounds;
let colliderBuonds = new Rectangle(this.x + this.localOffset.x, this.y + this.localOffset.y, shapeBounds.width, shapeBounds.height); let colliderBuonds = new Rectangle(this.entity.x, this.entity.y, shapeBounds.width, shapeBounds.height);
return colliderBuonds; return colliderBuonds;
} }
public get localOffset() {
return this._localOffset;
}
/** /**
* localOffset添加到实体 * localOffset添加到实体
*
* @param offset
*/ */
public set localOffset(value: Vector2) { public setLocalOffset(offset: Vector2): Collider{
this.setLocalOffset(value);
}
public setLocalOffset(offset: Vector2) {
if (this._localOffset != offset){ if (this._localOffset != offset){
this.unregisterColliderWithPhysicsSystem(); this.unregisterColliderWithPhysicsSystem();
this._localOffset = offset; this._localOffset = offset;
this._localOffsetLength = this._localOffset.length(); this._localOffsetLength = this._localOffset.length();
this.registerColliderWithPhysicsSystem(); this.registerColliderWithPhysicsSystem();
} }
return this;
} }
/** /**
@@ -85,15 +87,15 @@ abstract class Collider extends Component {
*/ */
public collidesWith(collider: Collider, motion: Vector2) { public collidesWith(collider: Collider, motion: Vector2) {
// 改变形状的位置,使它在移动后的位置,这样我们可以检查重叠 // 改变形状的位置,使它在移动后的位置,这样我们可以检查重叠
let oldPosition = this.shape.position; let oldPosition = this.entity.position;
this.shape.position = Vector2.add(this.shape.position, motion); this.entity.position = Vector2.add(this.entity.position, motion);
let result = this.shape.collidesWithShape(collider.shape); let result = this.shape.collidesWithShape(collider.shape);
if (result) if (result)
result.collider = collider; result.collider = collider;
// 将图形位置返回到检查前的位置 // 将图形位置返回到检查前的位置
this.shape.position = oldPosition; this.entity.position = oldPosition;
return result; return result;
} }
@@ -111,19 +113,17 @@ abstract class Collider extends Component {
// 这里我们需要大小*反尺度,因为当我们自动调整碰撞器的大小时,它需要没有缩放的渲染 // 这里我们需要大小*反尺度,因为当我们自动调整碰撞器的大小时,它需要没有缩放的渲染
let width = bounds.width / this.entity.scale.x; let width = bounds.width / this.entity.scale.x;
let height = bounds.height / this.entity.scale.y; let height = bounds.height / this.entity.scale.y;
// 圆碰撞器需要特别注意原点 // 圆碰撞器需要特别注意原点
if (this instanceof CircleCollider){ if (this instanceof CircleCollider){
let circleCollider = this as CircleCollider; let circleCollider = this as CircleCollider;
circleCollider.radius = Math.max(width, height) * 0.5; circleCollider.radius = Math.max(width, height) * 0.5;
this.localOffset = bounds.location;
} else { } else {
this.width = width; this.width = width;
this.height = height; this.height = height;
this.localOffset = bounds.location;
} }
// 获取渲染的中心,将其转移到本地坐标,并使用它作为碰撞器的localOffset
this.localOffset = Vector2.subtract(bounds.center, this.entity.position);
} else { } else {
console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it."); console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it.");
} }
@@ -154,8 +154,8 @@ abstract class Collider extends Component {
public update(){ public update(){
let renderable = this.entity.getComponent<RenderableComponent>(RenderableComponent); let renderable = this.entity.getComponent<RenderableComponent>(RenderableComponent);
if (renderable){ if (renderable){
this.$setX(renderable.x + this.localOffset.x); this.$setX(renderable.x);
this.$setY(renderable.y + this.localOffset.y); this.$setY(renderable.y);
} }
} }
} }
@@ -16,8 +16,6 @@ class PolygonCollider extends Collider {
if (isPolygonClosed) if (isPolygonClosed)
points.splice(points.length - 1, 1); points.splice(points.length - 1, 1);
let center = Polygon.findPolygonCenter(points);
this.setLocalOffset(center);
Polygon.recenterPolygonVerts(points); Polygon.recenterPolygonVerts(points);
this.shape = new Polygon(points); this.shape = new Polygon(points);
} }
@@ -48,8 +48,12 @@ class SpriteRenderer extends RenderableComponent{
/** 渲染处理 在每个模块中处理各自的渲染逻辑 */ /** 渲染处理 在每个模块中处理各自的渲染逻辑 */
public render(camera: Camera) { public render(camera: Camera) {
if (this.x != -camera.position.x + camera.origin.x ||
this.y != -camera.position.y + camera.origin.y) {
this.x = -camera.position.x + camera.origin.x; this.x = -camera.position.x + camera.origin.x;
this.y = -camera.position.y + camera.origin.y; this.y = -camera.position.y + camera.origin.y;
this.entity.onEntityTransformChanged(TransformComponent.position);
}
} }
public onRemovedFromEntity() { public onRemovedFromEntity() {
+280 -140
View File
@@ -1,164 +1,326 @@
class Entity extends egret.DisplayObjectContainer { module es {
private static _idGenerator: number; export class Entity {
public static _idGenerator: number;
public name: string; /**
public readonly id: number; *
/** 当前实体所属的场景 */ */
public scene: Scene; public scene: Scene;
/** 当前附加到此实体的所有组件的列表 */ /**
*
*/
public name: string;
/**
*
*/
public readonly id: number;
/**
* //
*/
public readonly transform: Transform;
/**
*
*/
public readonly components: ComponentList; public readonly components: ComponentList;
private _updateOrder: number = 0;
private _enabled: boolean = true;
public _isDestoryed: boolean;
private _tag: number = 0;
public componentBits: BitSet; /**
* 使使
public get isDestoryed(){ */
return this._isDestoryed; public get tag(): number {
}
public get position(){
return new Vector2(this.x, this.y);
}
public set position(value: Vector2){
this.$setX(value.x);
this.$setY(value.y);
this.onEntityTransformChanged(TransformComponent.position);
}
public get scale(){
return new Vector2(this.scaleX, this.scaleY);
}
public set scale(value: Vector2){
this.$setScaleX(value.x);
this.$setScaleY(value.y);
this.onEntityTransformChanged(TransformComponent.scale);
}
public set rotation(value: number){
this.$setRotation(value);
this.onEntityTransformChanged(TransformComponent.rotation);
}
public get rotation(){
return this.$getRotation();
}
public get enabled(){
return this._enabled;
}
public set enabled(value: boolean){
this.setEnabled(value);
}
public setEnabled(isEnabled: boolean){
if (this._enabled != isEnabled){
this._enabled = isEnabled;
}
return this;
}
public get tag(){
return this._tag; return this._tag;
} }
/**
* 使使
* @param value
*/
public set tag(value: number) { public set tag(value: number) {
this.setTag(value); this.setTag(value);
} }
public get stage(){ /**
if (!this.scene) * entity update方法的频率12
return null; */
public updateInterval: number = 1;
return this.scene.stage; /**
* /
*/
public get enabled() {
return this._enabled;
} }
constructor(name: string){ /**
super(); * /
this.name = name; * @param value
this.components = new ComponentList(this); */
this.id = Entity._idGenerator ++; public set enabled(value: boolean) {
this.setEnabled(value);
this.componentBits = new BitSet();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
private onAddToStage(){
this.onEntityTransformChanged(TransformComponent.position);
} }
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
*/
public get updateOrder() { public get updateOrder() {
return this._updateOrder; return this._updateOrder;
} }
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
* @param value
*/
public set updateOrder(value: number) { public set updateOrder(value: number) {
this.setUpdateOrder(value); this.setUpdateOrder(value);
} }
public roundPosition(){ public _isDestroyed: boolean;
this.position = Vector2Ext.round(this.position); /**
* destroytrue
*/
public get isDestroyed() {
return this._isDestroyed;
} }
public componentBits: BitSet;
private _tag: number = 0;
private _enabled: boolean = true;
private _updateOrder: number = 0;
public get parent(): Transform {
return this.transform.parent;
}
public set parent(value: Transform) {
this.transform.setParent(value);
}
public get childCount() {
return this.transform.childCount;
}
public get position(): Vector2 {
return this.transform.position;
}
public set position(value: Vector2) {
this.transform.setPosition(value.x, value.y);
}
public get rotation(): number {
return this.transform.rotation;
}
public set rotation(value: number) {
this.transform.setRotation(value);
}
public get scale(): Vector2 {
return this.transform.scale;
}
public set scale(value: Vector2) {
this.transform.setScale(value);
}
constructor(name: string) {
this.components = new ComponentList(this);
this.transform = new Transform(this);
this.name = name;
this.id = Entity._idGenerator++;
this.componentBits = new BitSet();
}
public onTransformChanged(comp: Transform.Component) {
// 通知我们的子项改变了位置
this.components.onEntityTransformChanged(comp);
}
/**
*
* @param tag
*/
public setTag(tag: number): Entity {
if (this._tag != tag) {
// 我们只有在已经有场景的情况下才会调用entityTagList。如果我们还没有场景,我们会被添加到entityTagList
if (this.scene)
this.scene.entities.removeFromTagList(this);
this._tag = tag;
if (this.scene)
this.scene.entities.addToTagList(this);
}
return this;
}
/**
*
* @param isEnabled
*/
public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled)
this.components.onEntityEnabled();
else
this.components.onEntityDisabled();
}
return this;
}
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
* @param updateOrder
*/
public setUpdateOrder(updateOrder: number) { public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) { if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder; this._updateOrder = updateOrder;
if (this.scene) { if (this.scene) {
// TODO: markEntityListSorted
// markTagUnsorted
} }
return this; return this;
} }
} }
public setTag(tag: number): Entity{ /**
if (this._tag != tag){ *
if (this.scene){ */
this.scene.entities.removeFromTagList(this); public destroy() {
} this._isDestroyed = true;
this._tag = tag; this.scene.entities.remove(this);
if (this.scene){ this.transform.parent = null;
this.scene.entities.addToTagList(this);
// 销毁所有子项
for (let i = this.transform.childCount - 1; i >= 0; i--) {
let child = this.transform.getChild(i);
child.entity.destroy();
} }
} }
return this; /**
* 下面的生命周期方法将被调用在组件上:OnRemovedFromEntity
*/
public detachFromScene() {
this.scene.entities.remove(this);
this.components.deregisterAllComponents();
for (let i = 0; i < this.transform.childCount; i++)
this.transform.getChild(i).entity.detachFromScene();
} }
/**
*
* @param newScene
*/
public attachToScene(newScene: Scene) { public attachToScene(newScene: Scene) {
this.scene = newScene; this.scene = newScene;
newScene.entities.add(this); newScene.entities.add(this);
this.components.registerAllComponents(); this.components.registerAllComponents();
for (let i = 0; i < this.numChildren; i ++){ for (let i = 0; i < this.transform.childCount; i++) {
(this.getChildAt(i) as Component).entity.attachToScene(newScene); this.transform.getChild(i).entity.attachToScene(newScene);
} }
} }
public detachFromScene(){ /**
this.scene.entities.remove(this); *
this.components.deregisterAllComponents(); * CopyFrom方法
* !!
* @param position
*/
public clone(position: Vector2 = new Vector2()): Entity {
let entity = new Entity(this.name + "(clone)");
entity.copyFrom(this);
entity.transform.position = position;
for (let i = 0; i < this.numChildren; i ++) return entity;
(this.getChildAt(i) as Component).entity.detachFromScene();
} }
/**
*
* @param entity
*/
protected copyFrom(entity: Entity) {
this.tag = entity.tag;
this.updateInterval = entity.updateInterval;
this.updateOrder = entity.updateOrder;
this.enabled = entity.enabled;
this.transform.scale = entity.transform.scale;
this.transform.rotation = entity.transform.rotation;
for (let i = 0; i < entity.components.count; i++)
this.addComponent(entity.components.buffer[i].clone());
for (let i = 0; i < entity.components._componentsToAdd.length; i++)
this.addComponent(entity.components._componentsToAdd[i].clone());
for (let i = 0; i < entity.transform.childCount; i++) {
let child = entity.transform.getChild(i).entity;
let childClone = child.clone();
childClone.transform.copyFrom(child.transform);
childClone.transform.parent = this.transform;
}
}
/**
*
*/
public onAddedToScene() {
}
/**
*
*/
public onRemovedFromScene() {
// 如果已经被销毁了,移走我们的组件。如果我们只是分离,我们需要保持我们的组件在实体上。
if (this._isDestroyed)
this.components.removeAllComponents();
}
/**
*
*/
public update() {
this.components.update();
}
/**
*
* @param component
*/
public addComponent<T extends Component>(component: T): T { public addComponent<T extends Component>(component: T): T {
component.entity = this; component.entity = this;
this.components.add(component); this.components.add(component);
this.addChild(component);
component.initialize(); component.initialize();
return component; return component;
} }
/**
* T的第一个组件并返回它null
* @param type
*/
public getComponent<T extends Component>(type): T {
return this.components.getComponent(type, false) as T;
}
/**
*
* @param type
*/
public hasComponent<T extends Component>(type) { public hasComponent<T extends Component>(type) {
return this.components.getComponent<T>(type, false) != null; return this.components.getComponent<T>(type, false) != null;
} }
/**
* T的第一个组件并返回它
* @param type
*/
public getOrCreateComponent<T extends Component>(type: T) { public getOrCreateComponent<T extends Component>(type: T) {
let comp = this.components.getComponent<T>(type, true); let comp = this.components.getComponent<T>(type, true);
if (!comp) { if (!comp) {
@@ -168,18 +330,27 @@ class Entity extends egret.DisplayObjectContainer {
return comp; return comp;
} }
public getComponent<T extends Component>(type): T{ /**
return this.components.getComponent(type, false) as T; * typeName类型的所有组件使
} * @param typeName
* @param componentList
*/
public getComponents(typeName: string | any, componentList?) { public getComponents(typeName: string | any, componentList?) {
return this.components.getComponents(typeName, componentList); return this.components.getComponents(typeName, componentList);
} }
private onEntityTransformChanged(comp: TransformComponent){ /**
this.components.onEntityTransformChanged(comp); *
* @param component
*/
public removeComponent(component: Component) {
this.components.remove(component);
} }
/**
* T的第一个组件
* @param type
*/
public removeComponentForType<T extends Component>(type) { public removeComponentForType<T extends Component>(type) {
let comp = this.getComponent<T>(type); let comp = this.getComponent<T>(type);
if (comp) { if (comp) {
@@ -190,48 +361,17 @@ class Entity extends egret.DisplayObjectContainer {
return false; return false;
} }
public removeComponent(component: Component){ /**
this.components.remove(component); *
} */
public removeAllComponents() { public removeAllComponents() {
for (let i = 0; i < this.components.count; i++) { for (let i = 0; i < this.components.count; i++) {
this.removeComponent(this.components.buffer[i]); this.removeComponent(this.components.buffer[i]);
} }
} }
public update(){ public toString(): string {
this.components.update(); return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`;
}
public onAddedToScene(){
}
public onRemovedFromScene(){
if (this._isDestoryed)
this.components.removeAllComponents();
}
public destroy(){
this._isDestoryed = true;
this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
this.scene.entities.remove(this);
this.removeChildren();
if (this.parent)
this.parent.removeChild(this);
for (let i = this.numChildren - 1; i >= 0; i --){
let child = this.getChildAt(i);
(child as Component).entity.destroy();
} }
} }
} }
enum TransformComponent {
rotation,
scale,
position
}
+251 -104
View File
@@ -1,99 +1,87 @@
module es {
/** 场景 */ /** 场景 */
class Scene extends egret.DisplayObjectContainer { export class Scene extends egret.DisplayObjectContainer {
/**
*
*/
public camera: Camera; public camera: Camera;
public readonly entities: EntityList; /**
public readonly renderableComponents: RenderableComponentList; * 使/使SceneManager.content
* contentManager来加载它们Nez不会卸载它们
*/
public readonly content: ContentManager; public readonly content: ContentManager;
/**
*
*/
public enablePostProcessing = true; public enablePostProcessing = true;
/**
private _renderers: Renderer[] = []; *
private _postProcessors: PostProcessor[] = []; */
private _didSceneBegin; public readonly entities: EntityList;
/**
*
*/
public readonly renderableComponents: RenderableComponentList;
/**
*
*/
public readonly entityProcessors: EntityProcessorList; public readonly entityProcessors: EntityProcessorList;
public _renderers: Renderer[] = [];
public readonly _postProcessors: PostProcessor[] = [];
public _didSceneBegin;
/**
* DefaultRenderer附加并准备使用
*/
public static createWithDefaultRenderer(){
let scene = new Scene();
scene.addRenderer(new DefaultRenderer())
return scene;
}
constructor() { constructor() {
super(); super();
this.entityProcessors = new EntityProcessorList();
this.renderableComponents = new RenderableComponentList();
this.entities = new EntityList(this); this.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager(); this.content = new ContentManager();
this.entityProcessors = new EntityProcessorList();
this.width = SceneManager.stage.stageWidth; this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight; this.height = SceneManager.stage.stageHeight;
this.addEventListener(egret.Event.ACTIVATE, this.onActive, this); this.initialize();
this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
}
public createEntity(name: string) {
let entity = new Entity(name);
entity.position = new Vector2(0, 0);
return this.addEntity(entity);
}
public addEntity(entity: Entity) {
this.entities.add(entity);
entity.scene = this;
this.addChild(entity);
for (let i = 0; i < entity.numChildren; i++)
this.addEntity((entity.getChildAt(i) as Component).entity);
return entity;
}
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
} }
/** /**
* EntitySystem处理器 * begin之前
* @param processor
*/ */
public addEntityProcessor(processor: EntitySystem) { public initialize(){}
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
public removeEntityProcessor(processor: EntitySystem) { /**
this.entityProcessors.remove(processor); * SceneManager将此场景设置为活动场景时
} */
public async onStart() {}
public getEntityProcessor<T extends EntitySystem>(): T { /**
return this.entityProcessors.getProcessor<T>(); * SceneManager从活动槽中删除此场景时调用
} */
public unload() { }
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this); /**
*
*/
public onActive() {}
return renderer; /**
} *
*/
public onDeactive() {}
public getRenderer<T extends Renderer>(type): T { public async begin() {
for (let i = 0; i < this._renderers.length; i++) { // 如果是场景转换需要在最顶层
if (this._renderers[i] instanceof type)
return this._renderers[i] as T;
}
return null;
}
public removeRenderer(renderer: Renderer) {
this._renderers.remove(renderer);
renderer.unload();
}
public begin() {
if (SceneManager.sceneTransition){ if (SceneManager.sceneTransition){
SceneManager.stage.addChildAt(this, SceneManager.stage.numChildren - 1); SceneManager.stage.addChildAt(this, SceneManager.stage.numChildren - 1);
}else{ }else{
@@ -104,7 +92,7 @@ class Scene extends egret.DisplayObjectContainer {
this.addRenderer(new DefaultRenderer()); this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染"); console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
} }
/** 初始化默认相机 */
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera()); this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
Physics.reset(); Physics.reset();
@@ -112,6 +100,8 @@ class Scene extends egret.DisplayObjectContainer {
if (this.entityProcessors) if (this.entityProcessors)
this.entityProcessors.begin(); this.entityProcessors.begin();
this.addEventListener(egret.Event.ACTIVATE, this.onActive, this);
this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight); this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
this._didSceneBegin = true; this._didSceneBegin = true;
@@ -135,70 +125,102 @@ class Scene extends egret.DisplayObjectContainer {
this.entities.removeAllEntities(); this.entities.removeAllEntities();
this.removeChildren(); this.removeChildren();
Physics.clear();
this.camera = null; this.camera = null;
this.content.dispose(); this.content.dispose();
if (this.entityProcessors) if (this.entityProcessors)
this.entityProcessors.end(); this.entityProcessors.end();
this.unload();
if (this.parent) if (this.parent)
this.parent.removeChild(this); this.parent.removeChild(this);
this.unload();
} }
protected async onStart() {
}
/** 场景激活 */
protected onActive() {
}
/** 场景失去焦点 */
protected onDeactive() {
}
protected unload() { }
public update() { public update() {
// 更新我们的列表,以防它们有任何变化
this.entities.updateLists(); this.entities.updateLists();
// 更新我们的实体解析器
if (this.entityProcessors) if (this.entityProcessors)
this.entityProcessors.update() this.entityProcessors.update();
// 更新我们的实体组
this.entities.update(); this.entities.update();
if (this.entityProcessors) if (this.entityProcessors)
this.entityProcessors.lateUpdate(); this.entityProcessors.lateUpdate();
// 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新
this.renderableComponents.updateList(); this.renderableComponents.updateList();
} }
public render() {
if (this._renderers.length == 0){
console.error("there are no renderers in the scene!");
return;
}
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].render(this);
}
}
/**
*
* SceneTransition请求渲染时
*/
public postRender() { public postRender() {
let enabledCounter = 0;
if (this.enablePostProcessing) { if (this.enablePostProcessing) {
for (let i = 0; i < this._postProcessors.length; i++) { for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enable) { if (this._postProcessors[i].enabled) {
let isEven = MathHelper.isEven(enabledCounter);
enabledCounter ++;
this._postProcessors[i].process(); this._postProcessors[i].process();
} }
} }
} }
} }
public render() { /**
for (let i = 0; i < this._renderers.length; i++) { *
this._renderers[i].render(this); * @param renderer
} */
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this);
return renderer;
} }
/**
* T的第一个渲染器
* @param type
*/
public getRenderer<T extends Renderer>(type): T {
for (let i = 0; i < this._renderers.length; i++) {
if (this._renderers[i] instanceof type)
return this._renderers[i] as T;
}
return null;
}
/**
*
* @param renderer
*/
public removeRenderer(renderer: Renderer) {
if (!this._renderers.contains(renderer))
return;
this._renderers.remove(renderer);
renderer.unload();
}
/**
* onAddedToScene使后处理器可以使用场景ContentManager加载资源
* @param postProcessor
*/
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{ public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{
this._postProcessors.push(postProcessor); this._postProcessors.push(postProcessor);
this._postProcessors.sort(); this._postProcessors.sort();
@@ -210,4 +232,129 @@ class Scene extends egret.DisplayObjectContainer {
return postProcessor; return postProcessor;
} }
/**
* T的第一个后处理器
* @param type
*/
public getPostProcessor<T extends PostProcessor>(type): T{
for (let i = 0; i < this._postProcessors.length; i ++){
if (this._postProcessors[i] instanceof type)
return this._postProcessors[i] as T;
}
return null;
}
/**
* unloadPostProcessorunload来释放资源
* @param postProcessor
*/
public removePostProcessor(postProcessor: PostProcessor){
if (!this._postProcessors.contains(postProcessor))
return;
this._postProcessors.remove(postProcessor);
postProcessor.unload();
}
/**
*
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name);
return this.addEntity(entity);
}
/**
*
* @param entity
*/
public addEntity(entity: Entity) {
if (this.entities.buffer.contains(entity))
console.warn(`You are attempting to add the same entity to a scene twice: ${entity}`);
this.entities.add(entity);
entity.scene = this;
for (let i = 0; i < entity.transform.childCount; i++)
this.addEntity(entity.transform.getChild(i).entity);
return entity;
}
/**
*
*/
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
/**
*
* @param name
*/
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
}
/**
*
* @param tag
*/
public findEntitiesWithTag(tag: number): Entity[]{
return this.entities.entitiesWithTag(tag);
}
/**
* T的所有实体
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[]{
return this.entities.entitiesOfType<T>(type);
}
/**
* T的组件
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
return this.entities.findComponentOfType<T>(type);
}
/**
* T的所有已启用已加载组件的列表
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[] {
return this.entities.findComponentsOfType<T>(type);
}
/**
* EntitySystem处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
/**
* EntitySystem处理器
* @param processor
*/
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
/**
* EntitySystem处理器
*/
public getEntityProcessor<T extends EntitySystem>(): T {
return this.entityProcessors.getProcessor<T>();
}
}
} }
+13
View File
@@ -12,6 +12,7 @@ class SceneManager {
public static content: ContentManager; public static content: ContentManager;
/** 简化对内部类的全局内容实例的访问 */ /** 简化对内部类的全局内容实例的访问 */
private static _instnace: SceneManager; private static _instnace: SceneManager;
private static timerRuler: TimeRuler;
public static get Instance(){ public static get Instance(){
return this._instnace; return this._instnace;
} }
@@ -25,6 +26,7 @@ class SceneManager {
SceneManager.stage = stage; SceneManager.stage = stage;
SceneManager.initialize(stage); SceneManager.initialize(stage);
SceneManager.timerRuler = new TimeRuler();
} }
public static get scene() { public static get scene() {
@@ -50,6 +52,7 @@ class SceneManager {
} }
public static update() { public static update() {
SceneManager.startDebugUpdate();
Time.update(egret.getTimer()); Time.update(egret.getTimer());
if (SceneManager._scene) { if (SceneManager._scene) {
@@ -74,6 +77,7 @@ class SceneManager {
} }
} }
SceneManager.endDebugUpdate();
SceneManager.render(); SceneManager.render();
} }
@@ -128,4 +132,13 @@ class SceneManager {
SceneManager.emitter.emit(CoreEvents.SceneChanged); SceneManager.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged(); Time.sceneChanged();
} }
private static startDebugUpdate(){
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
}
private static endDebugUpdate(){
TimeRuler.Instance.endMark("update");
}
} }
+138
View File
@@ -0,0 +1,138 @@
module es {
export class Transform {
/** 与此转换关联的实体 */
public readonly entity: Entity;
private _parent: Transform;
/**
*
*/
public get parent() {
return this._parent;
}
/**
*
* @param value
*/
public set parent(value: Transform) {
this.setParent(value);
}
/**
*
*/
public get childCount() {
return this._children.length;
}
/**
*
*/
public position: Vector2;
/**
*
*/
public rotation: number;
/**
*
*/
public scale: Vector2;
public _children: Transform[];
constructor(entity: Entity) {
this.entity = entity;
this.scale = Vector2.one;
this._children = [];
}
/**
*
* @param index
*/
public getChild(index: number): Transform {
return this._children[index];
}
/**
*
* @param parent
*/
public setParent(parent: Transform): Transform {
if (this._parent == parent)
return this;
if (!this._parent) {
this._parent._children.remove(this);
this._parent._children.push(this);
}
this._parent = parent;
return this;
}
/**
*
* @param x
* @param y
*/
public setPosition(x: number, y: number): Transform {
this.position = new Vector2(x, y);
return this;
}
/**
*
* @param degrees
*/
public setRotation(degrees: number): Transform {
this.rotation = degrees;
return this;
}
/**
*
* @param scale
*/
public setScale(scale: Vector2): Transform {
this.scale = scale;
return this;
}
/**
* 使
* @param pos
*/
public lookAt(pos: Vector2) {
let sign = this.position.x > pos.x ? -1 : 1;
let vectorToAlignTo = Vector2.normalize(Vector2.subtract(this.position, pos));
this.rotation = sign * Math.acos(Vector2.dot(vectorToAlignTo, Vector2.unitY));
}
/**
*
*/
public roundPosition() {
this.position = this.position.round();
}
/**
* transform属性进行拷贝
* @param transform
*/
public copyFrom(transform: Transform) {
this.position = transform.position;
this.rotation = transform.rotation;
this.scale = transform.scale;
}
}
}
module Transform {
export enum Component {
position,
scale,
rotation,
}
}
+48 -31
View File
@@ -1,12 +1,20 @@
class ComponentList { module es {
private _entity: Entity; export class ComponentList {
/** 添加到实体的组件列表 */ public _entity: Entity;
private _components: Component[] = [];
/** 添加到此框架的组件列表。用来对组件进行分组,这样我们就可以同时进行加工 */ /**
private _componentsToAdd: Component[] = []; *
/** 标记要删除此框架的组件列表。用来对组件进行分组,这样我们就可以同时进行加工 */ */
private _componentsToRemove: Component[] = []; public _components: Component[] = [];
private _tempBufferList: Component[] = []; /**
*
*/
public _componentsToAdd: Component[] = [];
/**
*
*/
public _componentsToRemove: Component[] = [];
public _tempBufferList: Component[] = [];
constructor(entity: Entity) { constructor(entity: Entity) {
this._entity = entity; this._entity = entity;
@@ -119,19 +127,8 @@ class ComponentList {
} }
} }
public onEntityTransformChanged(comp: TransformComponent) { public handleRemove(component: Component) {
for (let i = 0; i < this._components.length; i++) { // 处理渲染层列表
if (this._components[i].enabled)
this._components[i].onEntityTransformChanged(comp);
}
for (let i = 0; i < this._componentsToAdd.length; i++) {
if (this._componentsToAdd[i].enabled)
this._componentsToAdd[i].onEntityTransformChanged(comp);
}
}
private handleRemove(component: Component) {
if (component instanceof RenderableComponent) if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.remove(component); this._entity.scene.renderableComponents.remove(component);
@@ -142,6 +139,7 @@ class ComponentList {
component.entity = null; component.entity = null;
} }
/** /**
* T的第一个组件并返回它 * T的第一个组件并返回它
* (onAddedToEntity方法的组件) * (onAddedToEntity方法的组件)
@@ -209,16 +207,35 @@ class ComponentList {
public update() { public update() {
this.updateLists(); this.updateLists();
for (let i = 0; i < this._components.length; i++) { for (let i = 0; i < this._components.length; i++) {
let updatable = this._components[i]; let updatableComponent = this._components[i];
let updateableComponent;
if (updatable instanceof Component)
updateableComponent = updatable as Component;
if (updatable.enabled && if (updatableComponent.enabled &&
updateableComponent.enabled && (updatableComponent.updateInterval == 1 ||
(updateableComponent.updateInterval == 1 || Time.frameCount % updatableComponent.updateInterval == 0))
Time.frameCount % updateableComponent.updateInterval == 0)) updatableComponent.update();
updatable.update(); }
}
public onEntityTransformChanged(comp: Transform.Component) {
for (let i = 0; i < this._components.length; i++) {
if (this._components[i].enabled)
this._components[i].onEntityTransformChanged(comp);
}
for (let i = 0; i < this._componentsToAdd.length; i++) {
if (this._componentsToAdd[i].enabled)
this._componentsToAdd[i].onEntityTransformChanged(comp);
}
}
public onEntityEnabled() {
for (let i = 0; i < this._components.length; i++)
this._components[i].onEnabled();
}
public onEntityDisabled() {
for (let i = 0; i < this._components.length; i++)
this._components[i].onDisabled();
} }
} }
} }
+80 -1
View File
@@ -1,4 +1,5 @@
class EntityList{ module es {
export class EntityList{
public scene: Scene; public scene: Scene;
private _entitiesToRemove: Entity[] = []; private _entitiesToRemove: Entity[] = [];
private _entitiesToAdded: Entity[] = []; private _entitiesToAdded: Entity[] = [];
@@ -43,6 +44,83 @@ class EntityList{
return this._entitiesToAdded.firstOrDefault(entity => entity.name == name); return this._entitiesToAdded.firstOrDefault(entity => entity.name == name);
} }
/**
* ListPool.free将返回的列表放回池中
* @param tag
*/
public entitiesWithTag(tag: number){
let list = this.getTagList(tag);
let returnList = ListPool.obtain<Entity>();
for (let i = 0; i < list.length; i ++)
returnList.push(list[i]);
return returnList;
}
/**
* t类型的所有实体的列表ListPool.free放回池中
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[]{
let list = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i] instanceof type)
list.push(this._entities[i] as T);
}
this._entitiesToAdded.forEach(entity => {
if (entity instanceof type)
list.push(entity as T);
});
return list;
}
/**
* T的场景中找到的第一个组件
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].enabled){
let comp = this._entities[i].getComponent<T>(type);
if (comp)
return comp;
}
}
for (let i = 0; i < this._entitiesToAdded.length; i ++){
let entity = this._entitiesToAdded[i];
if (entity.enabled){
let comp = entity.getComponent<T>(type);
if (comp)
return comp;
}
}
return null;
}
/**
* t的场景中找到的所有组件ListPool.free放回池中
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[]{
let comps = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].enabled)
this._entities[i].getComponents(type, comps);
}
for (let i = 0; i < this._entitiesToAdded.length; i ++){
let entity = this._entitiesToAdded[i];
if (entity.enabled)
entity.getComponents(type,comps);
}
return comps;
}
public getTagList(tag: number){ public getTagList(tag: number){
let list = this._entityDict.get(tag); let list = this._entityDict.get(tag);
if (!list){ if (!list){
@@ -132,3 +210,4 @@ class EntityList{
} }
} }
} }
}
@@ -1,5 +1,5 @@
class PostProcessor { class PostProcessor {
public enable: boolean; public enabled: boolean;
public effect: egret.Filter; public effect: egret.Filter;
public scene: Scene; public scene: Scene;
public shape: egret.Shape; public shape: egret.Shape;
@@ -23,7 +23,7 @@ class PostProcessor {
"}"; "}";
constructor(effect: egret.Filter = null){ constructor(effect: egret.Filter = null){
this.enable = true; this.enabled = true;
this.effect = effect; this.effect = effect;
} }
+3
View File
@@ -3,6 +3,9 @@ class Circle extends Shape {
public radius: number; public radius: number;
public _originalRadius: number; public _originalRadius: number;
public center = new Vector2(); public center = new Vector2();
public get position(){
return new Vector2(this.parent.x, this.parent.y);
}
public get bounds(){ public get bounds(){
return new Rectangle().setEgretRect(this.getBounds()); return new Rectangle().setEgretRect(this.getBounds());
+15 -1
View File
@@ -1,13 +1,22 @@
///<reference path="./Shape.ts" /> ///<reference path="./Shape.ts" />
/**
*
*/
class Polygon extends Shape { class Polygon extends Shape {
/** 组成多边形的点。它们应该是CW和凸的。 */
public points: Vector2[]; public points: Vector2[];
private _polygonCenter: Vector2; private _polygonCenter: Vector2;
private _areEdgeNormalsDirty = true; private _areEdgeNormalsDirty = true;
protected _originalPoints: Vector2[]; protected _originalPoints: Vector2[];
public center = new Vector2(); public center = new Vector2();
/**
*
* 访
*/
public position: Vector2 = Vector2.zero;
public get bounds(){ public get bounds(){
return new Rectangle(0, 0, this.width, this.height); return new Rectangle(this.position.x, this.position.y, 0, 0);
} }
public _edgeNormals: Vector2[]; public _edgeNormals: Vector2[];
@@ -158,6 +167,11 @@ class Polygon extends Shape {
return { closestPoint: closestPoint, distanceSquared: distanceSquared, edgeNormal: edgeNormal }; return { closestPoint: closestPoint, distanceSquared: distanceSquared, edgeNormal: edgeNormal };
} }
public recalculateBounds(collider: Collider){
// 如果我们没有旋转或不关心TRS我们使用localOffset作为中心,我们会从那开始
}
public pointCollidesWithShape(point: Vector2): CollisionResult { public pointCollidesWithShape(point: Vector2): CollisionResult {
return ShapeCollisions.pointToPoly(point, this); return ShapeCollisions.pointToPoly(point, this);
} }
+16 -4
View File
@@ -1,8 +1,20 @@
abstract class Shape extends egret.DisplayObject { abstract class Shape {
public abstract bounds: Rectangle; /** 缓存的形状边界 内部字段 */
public position: Vector2 = Vector2.zero; public bounds: Rectangle;
public abstract center: Vector2; /**
*
* localOffset
*
*/
public center: Vector2;
/**
* entity.position
* //
*
*/
public position: Vector2;
public abstract recalculateBounds(collider: Collider);
public abstract pointCollidesWithShape(point: Vector2): CollisionResult; public abstract pointCollidesWithShape(point: Vector2): CollisionResult;
public abstract overlaps(other: Shape); public abstract overlaps(other: Shape);
public abstract collidesWithShape(other: Shape): CollisionResult; public abstract collidesWithShape(other: Shape): CollisionResult;
+2 -1
View File
@@ -63,6 +63,7 @@ class SpatialHash {
for (let y = p1.y; y <= p2.y; y++) { for (let y = p1.y; y <= p2.y; y++) {
// 如果没有单元格,我们需要创建它 // 如果没有单元格,我们需要创建它
let c = this.cellAtPosition(x, y, true); let c = this.cellAtPosition(x, y, true);
if (c.indexOf(collider) == -1)
c.push(collider); c.push(collider);
} }
} }
@@ -83,7 +84,7 @@ class SpatialHash {
let bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2); let bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2);
this._overlapTestCircle.radius = radius; this._overlapTestCircle.radius = radius;
this._overlapTestCircle.position = circleCenter; // this._overlapTestCircle.position = circleCenter;
let resultCounter = 0; let resultCounter = 0;
let aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask); let aabbBroadphaseResult = this.aabbBroadphase(bounds, null, layerMask);
+27 -20
View File
@@ -3,7 +3,7 @@
*/ */
class TimeRuler { class TimeRuler {
/** 最大条数 8 */ /** 最大条数 8 */
public static readonly maxBars = 0; public static readonly maxBars = 8;
/** */ /** */
public static readonly maxSamples = 256; public static readonly maxSamples = 256;
/** 每条的最大嵌套调用 */ /** 每条的最大嵌套调用 */
@@ -78,6 +78,8 @@ class TimeRuler {
let lock = new LockUtils(this._frameKey); let lock = new LockUtils(this._frameKey);
lock.lock().then(() => { lock.lock().then(() => {
this._updateCount = parseInt(egret.localStorage.getItem(this._frameKey), 10); this._updateCount = parseInt(egret.localStorage.getItem(this._frameKey), 10);
if (isNaN(this._updateCount))
this._updateCount = 0;
let count = this._updateCount; let count = this._updateCount;
count += 1; count += 1;
egret.localStorage.setItem(this._frameKey, count.toString()); egret.localStorage.setItem(this._frameKey, count.toString());
@@ -163,7 +165,7 @@ class TimeRuler {
// 获取注册的标记 // 获取注册的标记
let markerId = this._markerNameToIdMap.get(markerName); let markerId = this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
// 如果此标记未注册,则注册此标记。 // 如果此标记未注册,则注册此标记。
markerId = this.markers.length; markerId = this.markers.length;
this._markerNameToIdMap.set(markerName, markerId); this._markerNameToIdMap.set(markerName, markerId);
@@ -194,7 +196,7 @@ class TimeRuler {
} }
let markerId = this._markerNameToIdMap.get(markerName); let markerId = this._markerNameToIdMap.get(markerName);
if (!markerId) { if (isNaN(markerId)) {
throw new Error(`Marker ${markerName} is not registered. Make sure you specifed same name as you used for beginMark method`); throw new Error(`Marker ${markerName} is not registered. Make sure you specifed same name as you used for beginMark method`);
} }
@@ -298,8 +300,7 @@ class FrameLog {
constructor() { constructor() {
this.bars = new Array<MarkerCollection>(TimeRuler.maxBars); this.bars = new Array<MarkerCollection>(TimeRuler.maxBars);
for (let i = 0; i < TimeRuler.maxBars; ++i) this.bars.fill(new MarkerCollection(), 0, TimeRuler.maxBars);
this.bars[i] = new MarkerCollection();
} }
} }
@@ -308,16 +309,21 @@ class FrameLog {
*/ */
class MarkerCollection { class MarkerCollection {
public markers: Marker[] = new Array<Marker>(TimeRuler.maxSamples); public markers: Marker[] = new Array<Marker>(TimeRuler.maxSamples);
public markCount: number; public markCount: number = 0;
public markerNests: number[] = new Array<number>(TimeRuler.maxNestCall); public markerNests: number[] = new Array<number>(TimeRuler.maxNestCall);
public nestCount: number; public nestCount: number = 0;
constructor(){
this.markers.fill(new Marker(), 0, TimeRuler.maxSamples);
this.markerNests.fill(0, 0, TimeRuler.maxNestCall);
}
} }
class Marker { class Marker {
public markerId: number; public markerId: number = 0;
public beginTime: number; public beginTime: number = 0;
public endTime: number; public endTime: number = 0;
public color: number; public color: number = 0x000000;
} }
class MarkerInfo { class MarkerInfo {
@@ -326,17 +332,18 @@ class MarkerInfo {
constructor(name) { constructor(name) {
this.name = name; this.name = name;
this.logs.fill(new MarkerLog(), 0, TimeRuler.maxBars);
} }
} }
class MarkerLog { class MarkerLog {
public snapMin: number; public snapMin: number = 0;
public snapMax: number; public snapMax: number = 0;
public snapAvg: number; public snapAvg: number = 0;
public min: number; public min: number = 0;
public max: number; public max: number = 0;
public avg: number; public avg: number = 0;
public samples: number; public samples: number = 0;
public color: number; public color: number = 0x000000;
public initialized: boolean; public initialized: boolean = false;
} }
+1 -1
View File
@@ -36,7 +36,7 @@ class ListPool {
/** /**
* *
*/ */
public static obtain<T>(): Array<T>{ public static obtain<T>(): T[] {
if (this._objectQueue.length > 0) if (this._objectQueue.length > 0)
return this._objectQueue.shift(); return this._objectQueue.shift();