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