整理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;
+108 -114
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) {
this.x = -camera.position.x + camera.origin.x; if (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.x = -camera.position.x + camera.origin.x;
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,7 +5180,8 @@ 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);
c.push(collider); if (c.indexOf(collider) == -1)
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;
+66 -42
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) {
this.x = -camera.position.x + camera.origin.x; if (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.x = -camera.position.x + camera.origin.x;
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,7 +5180,8 @@ 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);
c.push(collider); if (c.indexOf(collider) == -1)
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
+131 -90
View File
@@ -1,96 +1,137 @@
abstract class Component extends egret.DisplayObjectContainer { module es {
public entity: Entity;
private _enabled: boolean = true;
public updateInterval: number = 1;
/** 允许用户为实体存入信息 */
public userData: any;
private _updateOrder = 0;
public get enabled(){
return this.entity ? this.entity.enabled && this._enabled : this._enabled;
}
public set enabled(value: boolean){
this.setEnabled(value);
}
public get localPosition(){
return new Vector2(this.entity.x + this.x, this.entity.y + this.y);
}
public setEnabled(isEnabled: boolean){
if (this._enabled != isEnabled){
this._enabled = isEnabled;
if (this._enabled){
this.onEnabled();
}else{
this.onDisabled();
}
}
return this;
}
/** 更新此实体上组件的顺序 */
public get updateOrder(){
return this._updateOrder;
}
/** 更新此实体上组件的顺序 */
public set updateOrder(value: number){
this.setUpdateOrder(value);
}
public setUpdateOrder(updateOrder: number){
if (this._updateOrder != updateOrder){
this._updateOrder = updateOrder;
}
return this;
}
public initialize(){
}
public onAddedToEntity(){
}
public onRemovedFromEntity(){
}
public onEnabled(){
}
public onDisabled(){
}
public debugRender(){
}
public update(){
}
/** /**
* *
* @param comp * - onAddedToEntity
* - OnEnabled
*
*
* - onRemovedFromEntity
*/ */
public onEntityTransformChanged(comp: TransformComponent){ export abstract class Component {
/**
*
*/
public entity: Entity;
} /**
* 访 this.entity.transform
*/
public get transform(): Transform {
return this.entity.transform;
}
/** 内部使用 运行时不应该调用 */ /**
public registerComponent(){ * onEnabled/onDisable
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this), false); */
this.entity.scene.entityProcessors.onComponentAdded(this.entity); public get enabled() {
} return this.entity ? this.entity.enabled && this._enabled : this._enabled;
}
public deregisterComponent(){ /**
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this)); * onEnabled/onDisable
this.entity.scene.entityProcessors.onComponentRemoved(this.entity); * @param value
*/
public set enabled(value: boolean) {
this.setEnabled(value);
}
/** 更新此实体上组件的顺序 */
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) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled) {
this.onEnabled();
} else {
this.onDisabled();
}
}
return this;
}
public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder;
}
return this;
}
/**
*
*/
public clone(): Component {
let component = ObjectUtils.clone<Component>(this);
component.entity = null;
return component;
}
} }
} }
+218 -216
View File
@@ -1,234 +1,236 @@
class Camera extends Component { module es {
private _zoom; export class Camera extends Component {
private _origin: Vector2 = Vector2.zero; private _zoom;
private _origin: Vector2 = Vector2.zero;
private _minimumZoom = 0.3; private _minimumZoom = 0.3;
private _maximumZoom = 3; private _maximumZoom = 3;
private _position: Vector2 = Vector2.zero; private _position: Vector2 = Vector2.zero;
/** /**
* cameraWindow * cameraWindow
* *
*/ */
public followLerp = 0.1; public followLerp = 0.1;
public deadzone: Rectangle = new Rectangle(); public deadzone: Rectangle = new Rectangle();
/** 锁定偏移量 默认中心 */ /** 锁定偏移量 默认中心 */
public focusOffset: Vector2 = new Vector2(); public focusOffset: Vector2 = new Vector2();
/** 是否地图锁定 如果锁定则需要设置mapSize属性 */ /** 是否地图锁定 如果锁定则需要设置mapSize属性 */
public mapLockEnabled: boolean = false; public mapLockEnabled: boolean = false;
/** 设置地图大小 默认从0 0左上角开始 只需要输入地图宽高 */ /** 设置地图大小 默认从0 0左上角开始 只需要输入地图宽高 */
public mapSize: Vector2 = new Vector2(); public mapSize: Vector2 = new Vector2();
/** 跟随的实体 设置后镜头将锁定目标为中心 */ /** 跟随的实体 设置后镜头将锁定目标为中心 */
public targetEntity: Entity; public targetEntity: Entity;
private _worldSpaceDeadZone: Rectangle = new Rectangle(); private _worldSpaceDeadZone: Rectangle = new Rectangle();
private _desiredPositionDelta: Vector2 = new Vector2(); private _desiredPositionDelta: Vector2 = new Vector2();
private _targetCollider: Collider; private _targetCollider: Collider;
/** 相机模式 */ /** 相机模式 */
public cameraStyle: CameraStyle = CameraStyle.lockOn; public cameraStyle: CameraStyle = CameraStyle.lockOn;
public get zoom(){ public get zoom(){
if (this._zoom == 0) if (this._zoom == 0)
return 1; return 1;
if (this._zoom < 1) if (this._zoom < 1)
return MathHelper.map(this._zoom, this._minimumZoom, 1, -1, 0); return MathHelper.map(this._zoom, this._minimumZoom, 1, -1, 0);
return MathHelper.map(this._zoom, 1, this._maximumZoom, 0, 1); return MathHelper.map(this._zoom, 1, this._maximumZoom, 0, 1);
}
public set zoom(value: number){
this.setZoom(value);
}
public get minimumZoom(){
return this._minimumZoom;
}
public set minimumZoom(value: number){
this.setMinimumZoom(value);
}
public get maximumZoom(){
return this._maximumZoom;
}
public set maximumZoom(value: number){
this.setMaximumZoom(value);
}
public get origin(){
return this._origin;
}
public set origin(value: Vector2){
if (this._origin != value){
this._origin = value;
}
}
public get position(){
return this._position;
}
public set position(value: Vector2){
this._position = value;
}
public get x(){
return this._position.x;
}
public set x(value: number){
this._position.x = value;
}
public get y(){
return this._position.y;
}
public set y(value: number){
this._position.y = value;
}
constructor() {
super();
this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight;
this.setZoom(0);
}
public onSceneSizeChanged(newWidth: number, newHeight: number){
let oldOrigin = this._origin;
this.origin = new Vector2(newWidth / 2, newHeight / 2);
this.entity.position = Vector2.add(this.entity.position, Vector2.subtract(this._origin, oldOrigin));
}
public setMinimumZoom(minZoom: number): Camera{
if (this._zoom < minZoom)
this._zoom = this.minimumZoom;
this._minimumZoom = minZoom;
return this;
}
public setMaximumZoom(maxZoom: number): Camera {
if (this._zoom > maxZoom)
this._zoom = maxZoom;
this._maximumZoom = maxZoom;
return this;
}
public setZoom(zoom: number): Camera{
let newZoom = MathHelper.clamp(zoom, -1, 1);
if (newZoom == 0){
this._zoom = 1;
} else if(newZoom < 0){
this._zoom = MathHelper.map(newZoom, -1, 0, this._minimumZoom, 1);
} else {
this._zoom = MathHelper.map(newZoom, 0, 1, 1, this._maximumZoom);
} }
SceneManager.scene.scaleX = this._zoom; public set zoom(value: number){
SceneManager.scene.scaleY = this._zoom; this.setZoom(value);
return this;
}
public setRotation(rotation: number): Camera {
SceneManager.scene.rotation = rotation;
return this;
}
public setPosition(position: Vector2){
this.entity.position = position;
return this;
}
public follow(targetEntity: Entity, cameraStyle: CameraStyle = CameraStyle.cameraWindow){
this.targetEntity = targetEntity;
this.cameraStyle = cameraStyle;
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
switch (this.cameraStyle){
case CameraStyle.cameraWindow:
let w = cameraBounds.width / 6;
let h = cameraBounds.height / 3;
this.deadzone = new Rectangle((cameraBounds.width - w) / 2, (cameraBounds.height - h) / 2, w, h);
break;
case CameraStyle.lockOn:
this.deadzone = new Rectangle(cameraBounds.width / 2, cameraBounds.height / 2, 10, 10);
break;
} }
}
public update(){ public get minimumZoom(){
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight); return this._minimumZoom;
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5)); }
this._worldSpaceDeadZone.x = this.position.x - halfScreen.x * SceneManager.scene.scaleX + this.deadzone.x + this.focusOffset.x;
this._worldSpaceDeadZone.y = this.position.y - halfScreen.y * SceneManager.scene.scaleY + this.deadzone.y + this.focusOffset.y;
this._worldSpaceDeadZone.width = this.deadzone.width;
this._worldSpaceDeadZone.height = this.deadzone.height;
if (this.targetEntity) public set minimumZoom(value: number){
this.updateFollow(); this.setMinimumZoom(value);
}
this.position = Vector2.lerp(this.position, Vector2.add(this.position, this._desiredPositionDelta), this.followLerp); public get maximumZoom(){
this.entity.roundPosition(); return this._maximumZoom;
}
if (this.mapLockEnabled){ public set maximumZoom(value: number){
this.position = this.clampToMapSize(this.position); this.setMaximumZoom(value);
}
public get origin(){
return this._origin;
}
public set origin(value: Vector2){
if (this._origin != value){
this._origin = value;
}
}
public get position(){
return this._position;
}
public set position(value: Vector2){
this._position = value;
}
public get x(){
return this._position.x;
}
public set x(value: number){
this._position.x = value;
}
public get y(){
return this._position.y;
}
public set y(value: number){
this._position.y = value;
}
constructor() {
super();
this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight;
this.setZoom(0);
}
public onSceneSizeChanged(newWidth: number, newHeight: number){
let oldOrigin = this._origin;
this.origin = new Vector2(newWidth / 2, newHeight / 2);
this.entity.position = Vector2.add(this.entity.position, Vector2.subtract(this._origin, oldOrigin));
}
public setMinimumZoom(minZoom: number): Camera{
if (this._zoom < minZoom)
this._zoom = this.minimumZoom;
this._minimumZoom = minZoom;
return this;
}
public setMaximumZoom(maxZoom: number): Camera {
if (this._zoom > maxZoom)
this._zoom = maxZoom;
this._maximumZoom = maxZoom;
return this;
}
public setZoom(zoom: number): Camera{
let newZoom = MathHelper.clamp(zoom, -1, 1);
if (newZoom == 0){
this._zoom = 1;
} else if(newZoom < 0){
this._zoom = MathHelper.map(newZoom, -1, 0, this._minimumZoom, 1);
} else {
this._zoom = MathHelper.map(newZoom, 0, 1, 1, this._maximumZoom);
}
SceneManager.scene.scaleX = this._zoom;
SceneManager.scene.scaleY = this._zoom;
return this;
}
public setRotation(rotation: number): Camera {
SceneManager.scene.rotation = rotation;
return this;
}
public setPosition(position: Vector2){
this.entity.position = position;
return this;
}
public follow(targetEntity: Entity, cameraStyle: CameraStyle = CameraStyle.cameraWindow){
this.targetEntity = targetEntity;
this.cameraStyle = cameraStyle;
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
switch (this.cameraStyle){
case CameraStyle.cameraWindow:
let w = cameraBounds.width / 6;
let h = cameraBounds.height / 3;
this.deadzone = new Rectangle((cameraBounds.width - w) / 2, (cameraBounds.height - h) / 2, w, h);
break;
case CameraStyle.lockOn:
this.deadzone = new Rectangle(cameraBounds.width / 2, cameraBounds.height / 2, 10, 10);
break;
}
}
public update(){
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5));
this._worldSpaceDeadZone.x = this.position.x - halfScreen.x * SceneManager.scene.scaleX + this.deadzone.x + this.focusOffset.x;
this._worldSpaceDeadZone.y = this.position.y - halfScreen.y * SceneManager.scene.scaleY + this.deadzone.y + this.focusOffset.y;
this._worldSpaceDeadZone.width = this.deadzone.width;
this._worldSpaceDeadZone.height = this.deadzone.height;
if (this.targetEntity)
this.updateFollow();
this.position = Vector2.lerp(this.position, Vector2.add(this.position, this._desiredPositionDelta), this.followLerp);
this.entity.roundPosition(); this.entity.roundPosition();
if (this.mapLockEnabled){
this.position = this.clampToMapSize(this.position);
this.entity.roundPosition();
}
}
private clampToMapSize(position: Vector2){
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5));
let cameraMax = new Vector2(this.mapSize.x - halfScreen.x, this.mapSize.y - halfScreen.y);
return Vector2.clamp(position, halfScreen, cameraMax);
}
private updateFollow(){
this._desiredPositionDelta.x = this._desiredPositionDelta.y = 0;
if (this.cameraStyle == CameraStyle.lockOn){
let targetX = this.targetEntity.position.x;
let targetY = this.targetEntity.position.y;
if (this._worldSpaceDeadZone.x > targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
else if(this._worldSpaceDeadZone.x < targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
if (this._worldSpaceDeadZone.y < targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
else if(this._worldSpaceDeadZone.y > targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
} else {
if (!this._targetCollider){
this._targetCollider = this.targetEntity.getComponent<Collider>(Collider);
if (!this._targetCollider)
return;
}
let targetBounds = this.targetEntity.getComponent<Collider>(Collider).bounds;
if (!this._worldSpaceDeadZone.containsRect(targetBounds)){
if (this._worldSpaceDeadZone.left > targetBounds.left)
this._desiredPositionDelta.x = targetBounds.left - this._worldSpaceDeadZone.left;
else if(this._worldSpaceDeadZone.right < targetBounds.right)
this._desiredPositionDelta.x = targetBounds.right - this._worldSpaceDeadZone.right;
if (this._worldSpaceDeadZone.bottom < targetBounds.bottom)
this._desiredPositionDelta.y = targetBounds.bottom - this._worldSpaceDeadZone.bottom;
else if(this._worldSpaceDeadZone.top > targetBounds.top)
this._desiredPositionDelta.y = targetBounds.top - this._worldSpaceDeadZone.top;
}
}
} }
} }
private clampToMapSize(position: Vector2){ export enum CameraStyle {
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight); lockOn,
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5)); cameraWindow,
let cameraMax = new Vector2(this.mapSize.x - halfScreen.x, this.mapSize.y - halfScreen.y);
return Vector2.clamp(position, halfScreen, cameraMax);
}
private updateFollow(){
this._desiredPositionDelta.x = this._desiredPositionDelta.y = 0;
if (this.cameraStyle == CameraStyle.lockOn){
let targetX = this.targetEntity.position.x;
let targetY = this.targetEntity.position.y;
if (this._worldSpaceDeadZone.x > targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
else if(this._worldSpaceDeadZone.x < targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
if (this._worldSpaceDeadZone.y < targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
else if(this._worldSpaceDeadZone.y > targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
} else {
if (!this._targetCollider){
this._targetCollider = this.targetEntity.getComponent<Collider>(Collider);
if (!this._targetCollider)
return;
}
let targetBounds = this.targetEntity.getComponent<Collider>(Collider).bounds;
if (!this._worldSpaceDeadZone.containsRect(targetBounds)){
if (this._worldSpaceDeadZone.left > targetBounds.left)
this._desiredPositionDelta.x = targetBounds.left - this._worldSpaceDeadZone.left;
else if(this._worldSpaceDeadZone.right < targetBounds.right)
this._desiredPositionDelta.x = targetBounds.right - this._worldSpaceDeadZone.right;
if (this._worldSpaceDeadZone.bottom < targetBounds.bottom)
this._desiredPositionDelta.y = targetBounds.bottom - this._worldSpaceDeadZone.bottom;
else if(this._worldSpaceDeadZone.top > targetBounds.top)
this._desiredPositionDelta.y = targetBounds.top - this._worldSpaceDeadZone.top;
}
}
} }
} }
enum CameraStyle {
lockOn,
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); if (this._localOffset != offset){
}
public setLocalOffset(offset: Vector2) {
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);
} }
+15 -11
View File
@@ -1,17 +1,17 @@
class SpriteRenderer extends RenderableComponent{ class SpriteRenderer extends RenderableComponent {
private _sprite: Sprite; private _sprite: Sprite;
protected bitmap: egret.Bitmap; protected bitmap: egret.Bitmap;
/** 应该由这个精灵显示的精灵 */ /** 应该由这个精灵显示的精灵 */
public get sprite(): Sprite{ public get sprite(): Sprite {
return this._sprite; return this._sprite;
} }
/** 应该由这个精灵显示的精灵 */ /** 应该由这个精灵显示的精灵 */
public set sprite(value: Sprite){ public set sprite(value: Sprite) {
this.setSprite(value); this.setSprite(value);
} }
public setSprite(sprite: Sprite): SpriteRenderer{ public setSprite(sprite: Sprite): SpriteRenderer {
this.removeChildren(); this.removeChildren();
this._sprite = sprite; this._sprite = sprite;
if (this._sprite) { if (this._sprite) {
@@ -24,7 +24,7 @@ class SpriteRenderer extends RenderableComponent{
return this; return this;
} }
public setColor(color: number): SpriteRenderer{ public setColor(color: number): SpriteRenderer {
let colorMatrix = [ let colorMatrix = [
1, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
@@ -40,23 +40,27 @@ class SpriteRenderer extends RenderableComponent{
return this; return this;
} }
public isVisibleFromCamera(camera: Camera): boolean{ public isVisibleFromCamera(camera: Camera): boolean {
this.isVisible = new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight).intersects(this.bounds); this.isVisible = new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight).intersects(this.bounds);
this.visible = this.isVisible; this.visible = this.isVisible;
return this.isVisible; return this.isVisible;
} }
/** 渲染处理 在每个模块中处理各自的渲染逻辑 */ /** 渲染处理 在每个模块中处理各自的渲染逻辑 */
public render(camera: Camera){ public render(camera: Camera) {
this.x = -camera.position.x + camera.origin.x; if (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.x = -camera.position.x + camera.origin.x;
this.y = -camera.position.y + camera.origin.y;
this.entity.onEntityTransformChanged(TransformComponent.position);
}
} }
public onRemovedFromEntity(){ public onRemovedFromEntity() {
if (this.parent) if (this.parent)
this.parent.removeChild(this); this.parent.removeChild(this);
} }
public reset(){ public reset() {
} }
} }
+335 -195
View File
@@ -1,237 +1,377 @@
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 readonly components: ComponentList; *
private _updateOrder: number = 0; */
private _enabled: boolean = true; public name: string;
public _isDestoryed: boolean; /**
private _tag: number = 0; *
*/
public readonly id: number;
/**
* //
*/
public readonly transform: Transform;
/**
*
*/
public readonly components: ComponentList;
public componentBits: BitSet; /**
* 使使
public get isDestoryed(){ */
return this._isDestoryed; public get tag(): number {
} return this._tag;
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; /**
} * 使使
* @param value
*/
public set tag(value: number) {
this.setTag(value);
}
public get tag(){ /**
return this._tag; * entity update方法的频率12
} */
public updateInterval: number = 1;
public set tag(value: number){ /**
this.setTag(value); * /
} */
public get enabled() {
return this._enabled;
}
public get stage(){ /**
if (!this.scene) * /
return null; * @param value
*/
return this.scene.stage; public set enabled(value: boolean) {
} this.setEnabled(value);
}
constructor(name: string){ /**
super(); * updateOrder还用于对scene.entities上的标签列表进行排序
this.name = name; */
this.components = new ComponentList(this); public get updateOrder() {
this.id = Entity._idGenerator ++; return this._updateOrder;
}
this.componentBits = new BitSet(); /**
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); * updateOrder还用于对scene.entities上的标签列表进行排序
} * @param value
*/
public set updateOrder(value: number) {
this.setUpdateOrder(value);
}
private onAddToStage(){ public _isDestroyed: boolean;
this.onEntityTransformChanged(TransformComponent.position); /**
} * destroytrue
*/
public get isDestroyed() {
return this._isDestroyed;
}
public get updateOrder(){ public componentBits: BitSet;
return this._updateOrder;
}
public set updateOrder(value: number){ private _tag: number = 0;
this.setUpdateOrder(value); private _enabled: boolean = true;
} private _updateOrder: number = 0;
public roundPosition(){ public get parent(): Transform {
this.position = Vector2Ext.round(this.position); return this.transform.parent;
} }
public setUpdateOrder(updateOrder: number){ public set parent(value: Transform) {
if (this._updateOrder != updateOrder){ this.transform.setParent(value);
this._updateOrder = updateOrder; }
if (this.scene){
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; return this;
} }
}
public setTag(tag: number): Entity{ /**
if (this._tag != tag){ *
if (this.scene){ * @param isEnabled
this.scene.entities.removeFromTagList(this); */
public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled)
this.components.onEntityEnabled();
else
this.components.onEntityDisabled();
} }
this._tag = tag;
if (this.scene){ return this;
this.scene.entities.addToTagList(this); }
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
* @param updateOrder
*/
public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder;
if (this.scene) {
// TODO: markEntityListSorted
// markTagUnsorted
}
return this;
} }
} }
return this; /**
} *
*/
public destroy() {
this._isDestroyed = true;
this.scene.entities.remove(this);
this.transform.parent = null;
public attachToScene(newScene: Scene){ // 销毁所有子项
this.scene = newScene; for (let i = this.transform.childCount - 1; i >= 0; i--) {
newScene.entities.add(this); let child = this.transform.getChild(i);
this.components.registerAllComponents(); child.entity.destroy();
}
for (let i = 0; i < this.numChildren; i ++){
(this.getChildAt(i) as Component).entity.attachToScene(newScene);
}
}
public detachFromScene(){
this.scene.entities.remove(this);
this.components.deregisterAllComponents();
for (let i = 0; i < this.numChildren; i ++)
(this.getChildAt(i) as Component).entity.detachFromScene();
}
public addComponent<T extends Component>(component: T): T{
component.entity = this;
this.components.add(component);
this.addChild(component);
component.initialize();
return component;
}
public hasComponent<T extends Component>(type){
return this.components.getComponent<T>(type, false) != null;
}
public getOrCreateComponent<T extends Component>(type: T){
let comp = this.components.getComponent<T>(type, true);
if (!comp){
comp = this.addComponent<T>(type);
} }
return comp; /**
} * 下面的生命周期方法将被调用在组件上:OnRemovedFromEntity
*/
public detachFromScene() {
this.scene.entities.remove(this);
this.components.deregisterAllComponents();
public getComponent<T extends Component>(type): T{ for (let i = 0; i < this.transform.childCount; i++)
return this.components.getComponent(type, false) as T; this.transform.getChild(i).entity.detachFromScene();
}
public getComponents(typeName: string | any, componentList?){
return this.components.getComponents(typeName, componentList);
}
private onEntityTransformChanged(comp: TransformComponent){
this.components.onEntityTransformChanged(comp);
}
public removeComponentForType<T extends Component>(type){
let comp = this.getComponent<T>(type);
if (comp){
this.removeComponent(comp);
return true;
} }
return false; /**
} *
* @param newScene
*/
public attachToScene(newScene: Scene) {
this.scene = newScene;
newScene.entities.add(this);
this.components.registerAllComponents();
public removeComponent(component: Component){ for (let i = 0; i < this.transform.childCount; i++) {
this.components.remove(component); this.transform.getChild(i).entity.attachToScene(newScene);
} }
public removeAllComponents(){
for (let i = 0; i < this.components.count; i ++){
this.removeComponent(this.components.buffer[i]);
} }
}
public update(){ /**
this.components.update(); *
} * CopyFrom方法
* !!
* @param position
*/
public clone(position: Vector2 = new Vector2()): Entity {
let entity = new Entity(this.name + "(clone)");
entity.copyFrom(this);
entity.transform.position = position;
public onAddedToScene(){ return entity;
}
} /**
*
* @param entity
*/
protected copyFrom(entity: Entity) {
this.tag = entity.tag;
this.updateInterval = entity.updateInterval;
this.updateOrder = entity.updateOrder;
this.enabled = entity.enabled;
public onRemovedFromScene(){ this.transform.scale = entity.transform.scale;
if (this._isDestoryed) this.transform.rotation = entity.transform.rotation;
this.components.removeAllComponents();
}
public destroy(){ for (let i = 0; i < entity.components.count; i++)
this._isDestoryed = true; this.addComponent(entity.components.buffer[i].clone());
this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); for (let i = 0; i < entity.components._componentsToAdd.length; i++)
this.addComponent(entity.components._componentsToAdd[i].clone());
this.scene.entities.remove(this); for (let i = 0; i < entity.transform.childCount; i++) {
this.removeChildren(); let child = entity.transform.getChild(i).entity;
let childClone = child.clone();
childClone.transform.copyFrom(child.transform);
childClone.transform.parent = this.transform;
}
}
if (this.parent) /**
this.parent.removeChild(this); *
*/
public onAddedToScene() {
}
for (let i = this.numChildren - 1; i >= 0; i --){ /**
let child = this.getChildAt(i); *
(child as Component).entity.destroy(); */
public onRemovedFromScene() {
// 如果已经被销毁了,移走我们的组件。如果我们只是分离,我们需要保持我们的组件在实体上。
if (this._isDestroyed)
this.components.removeAllComponents();
}
/**
*
*/
public update() {
this.components.update();
}
/**
*
* @param component
*/
public addComponent<T extends Component>(component: T): T {
component.entity = this;
this.components.add(component);
component.initialize();
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) {
return this.components.getComponent<T>(type, false) != null;
}
/**
* T的第一个组件并返回它
* @param type
*/
public getOrCreateComponent<T extends Component>(type: T) {
let comp = this.components.getComponent<T>(type, true);
if (!comp) {
comp = this.addComponent<T>(type);
}
return comp;
}
/**
* typeName类型的所有组件使
* @param typeName
* @param componentList
*/
public getComponents(typeName: string | any, componentList?) {
return this.components.getComponents(typeName, componentList);
}
/**
*
* @param component
*/
public removeComponent(component: Component) {
this.components.remove(component);
}
/**
* T的第一个组件
* @param type
*/
public removeComponentForType<T extends Component>(type) {
let comp = this.getComponent<T>(type);
if (comp) {
this.removeComponent(comp);
return true;
}
return false;
}
/**
*
*/
public removeAllComponents() {
for (let i = 0; i < this.components.count; i++) {
this.removeComponent(this.components.buffer[i]);
}
}
public toString(): string {
return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`;
} }
} }
} }
enum TransformComponent {
rotation,
scale,
position
}
+334 -187
View File
@@ -1,213 +1,360 @@
/** 场景 */ module es {
class Scene extends egret.DisplayObjectContainer { /** 场景 */
public camera: Camera; export class Scene extends egret.DisplayObjectContainer {
public readonly entities: EntityList; /**
public readonly renderableComponents: RenderableComponentList; *
public readonly content: ContentManager; */
public enablePostProcessing = true; public camera: Camera;
/**
* 使/使SceneManager.content
* contentManager来加载它们Nez不会卸载它们
*/
public readonly content: ContentManager;
/**
*
*/
public enablePostProcessing = true;
/**
*
*/
public readonly entities: EntityList;
/**
*
*/
public readonly renderableComponents: RenderableComponentList;
/**
*
*/
public readonly entityProcessors: EntityProcessorList;
private _renderers: Renderer[] = []; public _renderers: Renderer[] = [];
private _postProcessors: PostProcessor[] = []; public readonly _postProcessors: PostProcessor[] = [];
private _didSceneBegin; public _didSceneBegin;
public readonly entityProcessors: EntityProcessorList; /**
* DefaultRenderer附加并准备使用
constructor() { */
super(); public static createWithDefaultRenderer(){
this.entityProcessors = new EntityProcessorList(); let scene = new Scene();
this.renderableComponents = new RenderableComponentList(); scene.addRenderer(new DefaultRenderer())
this.entities = new EntityList(this); return scene;
this.content = new ContentManager();
this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight;
this.addEventListener(egret.Event.ACTIVATE, this.onActive, this);
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处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
public getEntityProcessor<T extends EntitySystem>(): T {
return this.entityProcessors.getProcessor<T>();
}
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this);
return renderer;
}
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; constructor() {
} super();
this.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager();
public removeRenderer(renderer: Renderer) { this.entityProcessors = new EntityProcessorList();
this._renderers.remove(renderer);
renderer.unload();
}
public begin() { this.width = SceneManager.stage.stageWidth;
if (SceneManager.sceneTransition){ this.height = SceneManager.stage.stageHeight;
SceneManager.stage.addChildAt(this, SceneManager.stage.numChildren - 1);
}else{
SceneManager.stage.addChild(this);
}
if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
/** 初始化默认相机 */
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
Physics.reset(); this.initialize();
if (this.entityProcessors)
this.entityProcessors.begin();
this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
this._didSceneBegin = true;
this.onStart();
}
public end() {
this._didSceneBegin = false;
this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this);
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].unload();
} }
for (let i = 0; i < this._postProcessors.length; i++) { /**
this._postProcessors[i].unload(); * begin之前
*/
public initialize(){}
/**
* SceneManager将此场景设置为活动场景时
*/
public async onStart() {}
/**
* SceneManager从活动槽中删除此场景时调用
*/
public unload() { }
/**
*
*/
public onActive() {}
/**
*
*/
public onDeactive() {}
public async begin() {
// 如果是场景转换需要在最顶层
if (SceneManager.sceneTransition){
SceneManager.stage.addChildAt(this, SceneManager.stage.numChildren - 1);
}else{
SceneManager.stage.addChild(this);
}
if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
Physics.reset();
if (this.entityProcessors)
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._didSceneBegin = true;
this.onStart();
} }
this.entities.removeAllEntities(); public end() {
this.removeChildren(); this._didSceneBegin = false;
Physics.clear(); this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this);
this.camera = null; for (let i = 0; i < this._renderers.length; i++) {
this.content.dispose(); this._renderers[i].unload();
}
if (this.entityProcessors)
this.entityProcessors.end();
this.unload();
if (this.parent)
this.parent.removeChild(this);
}
protected async onStart() {
}
/** 场景激活 */
protected onActive() {
}
/** 场景失去焦点 */
protected onDeactive() {
}
protected unload() { }
public update() {
this.entities.updateLists();
if (this.entityProcessors)
this.entityProcessors.update()
this.entities.update();
if (this.entityProcessors)
this.entityProcessors.lateUpdate();
this.renderableComponents.updateList();
}
public postRender() {
let enabledCounter = 0;
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) { this._postProcessors[i].unload();
let isEven = MathHelper.isEven(enabledCounter); }
enabledCounter ++;
this._postProcessors[i].process(); this.entities.removeAllEntities();
this.removeChildren();
this.camera = null;
this.content.dispose();
if (this.entityProcessors)
this.entityProcessors.end();
if (this.parent)
this.parent.removeChild(this);
this.unload();
}
public update() {
// 更新我们的列表,以防它们有任何变化
this.entities.updateLists();
// 更新我们的实体解析器
if (this.entityProcessors)
this.entityProcessors.update();
// 更新我们的实体组
this.entities.update();
if (this.entityProcessors)
this.entityProcessors.lateUpdate();
// 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新
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() {
if (this.enablePostProcessing) {
for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enabled) {
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();
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{ renderer.onAddedToScene(this);
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
if (this._didSceneBegin){ return renderer;
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
} }
return postProcessor; /**
* 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{
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
if (this._didSceneBegin){
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
}
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,
}
}
+206 -189
View File
@@ -1,224 +1,241 @@
class ComponentList { module es {
private _entity: Entity; export class ComponentList {
/** 添加到实体的组件列表 */ public _entity: Entity;
private _components: Component[] = [];
/** 添加到此框架的组件列表。用来对组件进行分组,这样我们就可以同时进行加工 */
private _componentsToAdd: Component[] = [];
/** 标记要删除此框架的组件列表。用来对组件进行分组,这样我们就可以同时进行加工 */
private _componentsToRemove: Component[] = [];
private _tempBufferList: Component[] = [];
constructor(entity: Entity) { /**
this._entity = entity; *
} */
public _components: Component[] = [];
/**
*
*/
public _componentsToAdd: Component[] = [];
/**
*
*/
public _componentsToRemove: Component[] = [];
public _tempBufferList: Component[] = [];
public get count() { constructor(entity: Entity) {
return this._components.length; this._entity = entity;
}
public get buffer() {
return this._components;
}
public add(component: Component) {
this._componentsToAdd.push(component);
}
public remove(component: Component) {
if (this._componentsToRemove.contains(component))
console.warn(`You are trying to remove a Component (${component}) that you already removed`)
// 这可能不是一个活动的组件,所以我们必须注意它是否还没有被处理,它可能正在同一帧中被删除
if (this._componentsToAdd.contains(component)) {
this._componentsToAdd.remove(component);
return;
} }
this._componentsToRemove.push(component); public get count() {
} return this._components.length;
/**
*
*/
public removeAllComponents() {
for (let i = 0; i < this._components.length; i++) {
this.handleRemove(this._components[i]);
} }
this._components.length = 0; public get buffer() {
this._componentsToAdd.length = 0; return this._components;
this._componentsToRemove.length = 0; }
}
public deregisterAllComponents() { public add(component: Component) {
for (let i = 0; i < this._components.length; i++) { this._componentsToAdd.push(component);
let component = this._components[i]; }
public remove(component: Component) {
if (this._componentsToRemove.contains(component))
console.warn(`You are trying to remove a Component (${component}) that you already removed`)
// 这可能不是一个活动的组件,所以我们必须注意它是否还没有被处理,它可能正在同一帧中被删除
if (this._componentsToAdd.contains(component)) {
this._componentsToAdd.remove(component);
return;
}
this._componentsToRemove.push(component);
}
/**
*
*/
public removeAllComponents() {
for (let i = 0; i < this._components.length; i++) {
this.handleRemove(this._components[i]);
}
this._components.length = 0;
this._componentsToAdd.length = 0;
this._componentsToRemove.length = 0;
}
public deregisterAllComponents() {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
// 处理渲染层列表
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.remove(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
}
}
public registerAllComponents() {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.add(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
}
}
/**
*
*/
public updateLists() {
if (this._componentsToRemove.length > 0) {
for (let i = 0; i < this._componentsToRemove.length; i++) {
this.handleRemove(this._componentsToRemove[i]);
this._components.remove(this._componentsToRemove[i]);
}
this._componentsToRemove.length = 0;
}
if (this._componentsToAdd.length > 0) {
for (let i = 0, count = this._componentsToAdd.length; i < count; i++) {
let component = this._componentsToAdd[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.add(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
this._components.push(component);
this._tempBufferList.push(component);
}
// 在调用onAddedToEntity之前清除,以防添加更多组件
this._componentsToAdd.length = 0;
// 现在所有的组件都添加到了场景中,我们再次循环并调用onAddedToEntity/onEnabled
for (let i = 0; i < this._tempBufferList.length; i++) {
let component = this._tempBufferList[i];
component.onAddedToEntity();
// enabled检查实体和组件
if (component.enabled) {
component.onEnabled();
}
}
this._tempBufferList.length = 0;
}
}
public handleRemove(component: Component) {
// 处理渲染层列表 // 处理渲染层列表
if (component instanceof RenderableComponent) if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.remove(component); this._entity.scene.renderableComponents.remove(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false); this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity); this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
}
}
public registerAllComponents() { component.onRemovedFromEntity();
for (let i = 0; i < this._components.length; i++) { component.entity = null;
let component = this._components[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.add(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
}
}
/**
*
*/
public updateLists() {
if (this._componentsToRemove.length > 0) {
for (let i = 0; i < this._componentsToRemove.length; i++) {
this.handleRemove(this._componentsToRemove[i]);
this._components.remove(this._componentsToRemove[i]);
}
this._componentsToRemove.length = 0;
} }
if (this._componentsToAdd.length > 0) {
for (let i = 0, count = this._componentsToAdd.length; i < count; i++) {
let component = this._componentsToAdd[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.add(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component)); /**
this._entity.scene.entityProcessors.onComponentAdded(this._entity); * T的第一个组件并返回它
* (onAddedToEntity方法的组件)
this._components.push(component); * null
this._tempBufferList.push(component); * @param type
} * @param onlyReturnInitializedComponents
*/
// 在调用onAddedToEntity之前清除,以防添加更多组件 public getComponent<T extends Component>(type, onlyReturnInitializedComponents: boolean): T {
this._componentsToAdd.length = 0; for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
// 现在所有的组件都添加到了场景中,我们再次循环并调用onAddedToEntity/onEnabled
for (let i = 0; i < this._tempBufferList.length; i++) {
let component = this._tempBufferList[i];
component.onAddedToEntity();
// enabled检查实体和组件
if (component.enabled) {
component.onEnabled();
}
}
this._tempBufferList.length = 0;
}
}
public onEntityTransformChanged(comp: TransformComponent) {
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)
this._entity.scene.renderableComponents.remove(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
component.onRemovedFromEntity();
component.entity = null;
}
/**
* T的第一个组件并返回它
* (onAddedToEntity方法的组件)
* null
* @param type
* @param onlyReturnInitializedComponents
*/
public getComponent<T extends Component>(type, onlyReturnInitializedComponents: boolean): T {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (component instanceof type)
return component as T;
}
// 我们可以选择检查挂起的组件,以防addComponent和getComponent在同一个框架中被调用
if (!onlyReturnInitializedComponents) {
for (let i = 0; i < this._componentsToAdd.length; i++) {
let component = this._componentsToAdd[i];
if (component instanceof type) if (component instanceof type)
return component as T; return component as T;
} }
// 我们可以选择检查挂起的组件,以防addComponent和getComponent在同一个框架中被调用
if (!onlyReturnInitializedComponents) {
for (let i = 0; i < this._componentsToAdd.length; i++) {
let component = this._componentsToAdd[i];
if (component instanceof type)
return component as T;
}
}
return null;
} }
return null; /**
} * T类型的所有组件使
* @param typeName
* @param components
*/
public getComponents(typeName: string | any, components?) {
if (!components)
components = [];
/** for (let i = 0; i < this._components.length; i++) {
* T类型的所有组件使 let component = this._components[i];
* @param typeName if (typeof (typeName) == "string") {
* @param components if (egret.is(component, typeName)) {
*/ components.push(component);
public getComponents(typeName: string | any, components?) { }
if (!components) } else {
components = []; if (component instanceof typeName) {
components.push(component);
}
}
}
for (let i = 0; i < this._components.length; i++) { for (let i = 0; i < this._componentsToAdd.length; i++) {
let component = this._components[i]; let component = this._componentsToAdd[i];
if (typeof (typeName) == "string") { if (typeof (typeName) == "string") {
if (egret.is(component, typeName)) { if (egret.is(component, typeName)) {
components.push(component); components.push(component);
} }
} else { } else {
if (component instanceof typeName) { if (component instanceof typeName) {
components.push(component); components.push(component);
}
} }
} }
return components;
}
public update() {
this.updateLists();
for (let i = 0; i < this._components.length; i++) {
let updatableComponent = this._components[i];
if (updatableComponent.enabled &&
(updatableComponent.updateInterval == 1 ||
Time.frameCount % updatableComponent.updateInterval == 0))
updatableComponent.update();
}
} }
for (let i = 0; i < this._componentsToAdd.length; i++) { public onEntityTransformChanged(comp: Transform.Component) {
let component = this._componentsToAdd[i]; for (let i = 0; i < this._components.length; i++) {
if (typeof (typeName) == "string") { if (this._components[i].enabled)
if (egret.is(component, typeName)) { this._components[i].onEntityTransformChanged(comp);
components.push(component); }
}
} else { for (let i = 0; i < this._componentsToAdd.length; i++) {
if (component instanceof typeName) { if (this._componentsToAdd[i].enabled)
components.push(component); this._componentsToAdd[i].onEntityTransformChanged(comp);
}
} }
} }
return components; public onEntityEnabled() {
} for (let i = 0; i < this._components.length; i++)
this._components[i].onEnabled();
}
public update() { public onEntityDisabled() {
this.updateLists(); for (let i = 0; i < this._components.length; i++)
for (let i = 0; i < this._components.length; i++) { this._components[i].onDisabled();
let updatable = this._components[i];
let updateableComponent;
if (updatable instanceof Component)
updateableComponent = updatable as Component;
if (updatable.enabled &&
updateableComponent.enabled &&
(updateableComponent.updateInterval == 1 ||
Time.frameCount % updateableComponent.updateInterval == 0))
updatable.update();
} }
} }
} }
+191 -112
View File
@@ -1,134 +1,213 @@
class EntityList{ module es {
public scene: Scene; export class EntityList{
private _entitiesToRemove: Entity[] = []; public scene: Scene;
private _entitiesToAdded: Entity[] = []; private _entitiesToRemove: Entity[] = [];
private _tempEntityList: Entity[] = []; private _entitiesToAdded: Entity[] = [];
private _entities: Entity[] = []; private _tempEntityList: Entity[] = [];
private _entityDict: Map<number, Entity[]> = new Map<number, Entity[]>(); private _entities: Entity[] = [];
private _unsortedTags: number[] = []; private _entityDict: Map<number, Entity[]> = new Map<number, Entity[]>();
private _unsortedTags: number[] = [];
constructor(scene: Scene){ constructor(scene: Scene){
this.scene = scene; this.scene = scene;
}
public get count(){
return this._entities.length;
}
public get buffer(){
return this._entities;
}
public add(entity: Entity){
if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity);
}
public remove(entity: Entity){
if (this._entitiesToAdded.contains(entity)){
this._entitiesToAdded.remove(entity);
return;
} }
if (!this._entitiesToRemove.contains(entity)) public get count(){
this._entitiesToRemove.push(entity); return this._entities.length;
}
public findEntity(name: string){
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].name == name)
return this._entities[i];
} }
return this._entitiesToAdded.firstOrDefault(entity => entity.name == name); public get buffer(){
} return this._entities;
public getTagList(tag: number){
let list = this._entityDict.get(tag);
if (!list){
list = [];
this._entityDict.set(tag, list);
} }
return this._entityDict.get(tag); public add(entity: Entity){
} if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity);
public addToTagList(entity: Entity){
let list = this.getTagList(entity.tag);
if (!list.contains(entity)){
list.push(entity);
this._unsortedTags.push(entity.tag);
}
}
public removeFromTagList(entity: Entity){
let list = this._entityDict.get(entity.tag);
if (list){
list.remove(entity);
}
}
public update(){
for (let i = 0; i < this._entities.length; i++){
let entity = this._entities[i];
if (entity.enabled)
entity.update();
}
}
public removeAllEntities(){
this._entitiesToAdded.length = 0;
this.updateLists();
for (let i = 0; i < this._entities.length; i ++){
this._entities[i]._isDestoryed = true;
this._entities[i].onRemovedFromScene();
this._entities[i].scene = null;
} }
this._entities.length = 0; public remove(entity: Entity){
this._entityDict.clear(); if (this._entitiesToAdded.contains(entity)){
} this._entitiesToAdded.remove(entity);
return;
}
public updateLists(){ if (!this._entitiesToRemove.contains(entity))
if (this._entitiesToRemove.length > 0){ this._entitiesToRemove.push(entity);
let temp = this._entitiesToRemove; }
this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
this._entities.remove(entity);
entity.scene = null;
this.scene.entityProcessors.onEntityRemoved(entity); public findEntity(name: string){
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].name == name)
return this._entities[i];
}
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);
}); });
this._tempEntityList.length = 0; return list;
} }
if (this._entitiesToAdded.length > 0){ /**
let temp = this._entitiesToAdded; * T的场景中找到的第一个组件
this._entitiesToAdded = this._tempEntityList; * @param type
this._tempEntityList = temp; */
this._tempEntityList.forEach(entity => { public findComponentOfType<T extends Component>(type): T {
if (!this._entities.contains(entity)){ for (let i = 0; i < this._entities.length; i ++){
this._entities.push(entity); if (this._entities[i].enabled){
entity.scene = this.scene; let comp = this._entities[i].getComponent<T>(type);
if (comp)
this.scene.entityProcessors.onEntityAdded(entity) return comp;
} }
}); }
this._tempEntityList.forEach(entity => entity.onAddedToScene()); for (let i = 0; i < this._entitiesToAdded.length; i ++){
this._tempEntityList.length = 0; let entity = this._entitiesToAdded[i];
if (entity.enabled){
let comp = entity.getComponent<T>(type);
if (comp)
return comp;
}
}
return null;
} }
if (this._unsortedTags.length > 0){ /**
this._unsortedTags.forEach(tag => { * t的场景中找到的所有组件ListPool.free放回池中
this._entityDict.get(tag).sort(); * @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);
}
this._unsortedTags.length = 0; 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){
let list = this._entityDict.get(tag);
if (!list){
list = [];
this._entityDict.set(tag, list);
}
return this._entityDict.get(tag);
}
public addToTagList(entity: Entity){
let list = this.getTagList(entity.tag);
if (!list.contains(entity)){
list.push(entity);
this._unsortedTags.push(entity.tag);
}
}
public removeFromTagList(entity: Entity){
let list = this._entityDict.get(entity.tag);
if (list){
list.remove(entity);
}
}
public update(){
for (let i = 0; i < this._entities.length; i++){
let entity = this._entities[i];
if (entity.enabled)
entity.update();
}
}
public removeAllEntities(){
this._entitiesToAdded.length = 0;
this.updateLists();
for (let i = 0; i < this._entities.length; i ++){
this._entities[i]._isDestoryed = true;
this._entities[i].onRemovedFromScene();
this._entities[i].scene = null;
}
this._entities.length = 0;
this._entityDict.clear();
}
public updateLists(){
if (this._entitiesToRemove.length > 0){
let temp = this._entitiesToRemove;
this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
this._entities.remove(entity);
entity.scene = null;
this.scene.entityProcessors.onEntityRemoved(entity);
});
this._tempEntityList.length = 0;
}
if (this._entitiesToAdded.length > 0){
let temp = this._entitiesToAdded;
this._entitiesToAdded = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
if (!this._entities.contains(entity)){
this._entities.push(entity);
entity.scene = this.scene;
this.scene.entityProcessors.onEntityAdded(entity)
}
});
this._tempEntityList.forEach(entity => entity.onAddedToScene());
this._tempEntityList.length = 0;
}
if (this._unsortedTags.length > 0){
this._unsortedTags.forEach(tag => {
this._entityDict.get(tag).sort();
});
this._unsortedTags.length = 0;
}
} }
} }
} }
@@ -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;
+3 -2
View File
@@ -63,7 +63,8 @@ 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);
c.push(collider); if (c.indexOf(collider) == -1)
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();