reformat code

This commit is contained in:
yhh
2020-07-28 16:25:20 +08:00
parent 5994f0bee3
commit 514572f291
103 changed files with 2896 additions and 2839 deletions

View File

@@ -12,6 +12,10 @@ module es {
* 此组件附加的实体
*/
public entity: Entity;
/**
* 更新该组件的时间间隔。这与实体的更新间隔无关。
*/
public updateInterval: number = 1;
/**
* 快速访问 this.entity.transform
@@ -20,6 +24,8 @@ module es {
return this.entity.transform;
}
private _enabled: boolean = true;
/**
* 如果组件和实体都已启用则为。当启用该组件时将调用该组件的生命周期方法。状态的改变会导致调用onEnabled/onDisable。
*/
@@ -35,6 +41,8 @@ module es {
this.setEnabled(value);
}
private _updateOrder = 0;
/** 更新此实体上组件的顺序 */
public get updateOrder() {
return this._updateOrder;
@@ -45,14 +53,6 @@ module es {
this.setUpdateOrder(value);
}
/**
* 更新该组件的时间间隔。这与实体的更新间隔无关。
*/
public updateInterval: number = 1;
private _enabled: boolean = true;
private _updateOrder = 0;
/**
* 当此组件已分配其实体,但尚未添加到实体的活动组件列表时调用。有用的东西,如物理组件,需要访问转换来修改碰撞体的属性。
*/

View File

@@ -12,6 +12,46 @@ module es {
}
export class Camera extends Component {
public _inset: CameraInset = new CameraInset();
public _areMatrixedDirty: boolean = true;
public _areBoundsDirty: boolean = true;
public _isProjectionMatrixDirty = true;
/**
* 如果相机模式为cameraWindow 则会进行缓动移动
* 该值为移动速度
*/
public followLerp = 0.1;
/**
* 在cameraWindow模式下宽度/高度被用做边界框,允许在不移动相机的情况下移动
* 在lockOn模式下只使用deadZone的x/y值 你可以通过直接setCenteredDeadzone重写它来自定义deadZone
*/
public deadzone: Rectangle = new Rectangle();
/**
* 相机聚焦于屏幕中心的偏移
*/
public focusOffset: Vector2 = Vector2.zero;
/**
* 如果为true 相机位置则不会超出地图矩形0, 0, mapwidth, mapheight
*/
public mapLockEnabled: boolean = false;
/**
* 當前地圖映射的寬度和高度
*/
public mapSize: Vector2 = Vector2.zero;
public _targetEntity: Entity;
public _targetCollider: Collider;
public _desiredPositionDelta: Vector2 = new Vector2();
public _cameraStyle: CameraStyle;
public _worldSpaceDeadZone: Rectangle = new Rectangle();
constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) {
super();
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
this.setZoom(0);
}
/**
* 对entity.transform.position的快速访问
*/
@@ -42,6 +82,8 @@ module es {
this.entity.transform.rotation = value;
}
public _zoom;
/**
* 缩放值应该在-1和1之间、然后将该值从minimumZoom转换为maximumZoom。
* 允许你设置适当的最小/最大值,然后使用更直观的-1到1的映射来更改缩放
@@ -65,6 +107,8 @@ module es {
this.setZoom(value);
}
public _minimumZoom = 0.3;
/**
* 相机变焦可以达到的最小非缩放值0-number.max。默认为0.3
*/
@@ -80,6 +124,8 @@ module es {
this.setMinimumZoom(value);
}
public _maximumZoom = 3;
/**
* 相机变焦可以达到的最大非缩放值0-number.max。默认为3
*/
@@ -95,20 +141,22 @@ module es {
this.setMaximumZoom(value);
}
public _bounds: Rectangle = new Rectangle();
/**
* 相机的世界-空间边界
*/
public get bounds(){
public get bounds() {
if (this._areMatrixedDirty)
this.updateMatrixes();
if (this._areBoundsDirty){
if (this._areBoundsDirty) {
// 旋转或非旋转的边界都需要左上角和右下角
let topLeft = this.screenToWorldPoint(new Vector2(this._inset.left, this._inset.top));
let bottomRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right,
Core.graphicsDevice.viewport.height - this._inset.bottom));
if (this.entity.transform.rotation != 0){
if (this.entity.transform.rotation != 0) {
// 特别注意旋转的边界。我们需要找到绝对的最小/最大值并从中创建边界
let topRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right,
this._inset.top));
@@ -135,6 +183,8 @@ module es {
return this._bounds;
}
public _transformMatrix: Matrix2D = new Matrix2D().identity();
/**
* 用于从世界坐标转换到屏幕
*/
@@ -144,6 +194,8 @@ module es {
return this._transformMatrix;
}
public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity();
/**
* 用于从屏幕坐标到世界的转换
*/
@@ -153,6 +205,8 @@ module es {
return this._inverseTransformMatrix;
}
public _origin: Vector2 = Vector2.zero;
public get origin() {
return this._origin;
}
@@ -164,56 +218,6 @@ module es {
}
}
public _zoom;
public _minimumZoom = 0.3;
public _maximumZoom = 3;
public _bounds: Rectangle = new Rectangle();
public _inset: CameraInset = new CameraInset();
public _transformMatrix: Matrix2D = new Matrix2D().identity();
public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity();
public _origin: Vector2 = Vector2.zero;
public _areMatrixedDirty: boolean = true;
public _areBoundsDirty: boolean = true;
public _isProjectionMatrixDirty = true;
/**
* 如果相机模式为cameraWindow 则会进行缓动移动
* 该值为移动速度
*/
public followLerp = 0.1;
/**
* 在cameraWindow模式下宽度/高度被用做边界框,允许在不移动相机的情况下移动
* 在lockOn模式下只使用deadZone的x/y值 你可以通过直接setCenteredDeadzone重写它来自定义deadZone
*/
public deadzone: Rectangle = new Rectangle();
/**
* 相机聚焦于屏幕中心的偏移
*/
public focusOffset: Vector2 = Vector2.zero;
/**
* 如果为true 相机位置则不会超出地图矩形0, 0, mapwidth, mapheight
*/
public mapLockEnabled: boolean = false;
/**
* 當前地圖映射的寬度和高度
*/
public mapSize: Vector2 = Vector2.zero;
public _targetEntity: Entity;
public _targetCollider: Collider;
public _desiredPositionDelta: Vector2 = new Vector2();
public _cameraStyle: CameraStyle;
public _worldSpaceDeadZone: Rectangle = new Rectangle();
constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) {
super();
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
this.setZoom(0);
}
/**
* 当场景渲染目标的大小发生变化时,我们会更新相机的原点并调整它的位置以保持它原来的位置
* @param newWidth
@@ -226,33 +230,6 @@ module es {
this.entity.transform.position = Vector2.add(this.entity.transform.position, Vector2.subtract(this._origin, oldOrigin));
}
protected updateMatrixes(){
if (!this._areMatrixedDirty)
return;
let tempMat: Matrix2D;
this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y);
if (this._zoom != 1){
tempMat = Matrix2D.create().scale(this._zoom, this._zoom);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
if (this.entity.transform.rotation != 0){
tempMat = Matrix2D.create().rotate(this.entity.transform.rotation);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y);
this._transformMatrix =this._transformMatrix.multiply(tempMat);
this._inverseTransformMatrix = this._transformMatrix.invert();
// 无论何时矩阵改变边界都是无效的
this._areBoundsDirty = true;
this._areMatrixedDirty = false;
}
/**
* 设置用于从视口边缘插入摄像机边界的量
* @param left
@@ -357,7 +334,7 @@ module es {
* 将一个点从世界坐标转换到屏幕
* @param worldPosition
*/
public worldToScreenPoint(worldPosition: Vector2): Vector2{
public worldToScreenPoint(worldPosition: Vector2): Vector2 {
this.updateMatrixes();
worldPosition = Vector2.transform(worldPosition, this._transformMatrix);
return worldPosition;
@@ -367,7 +344,7 @@ module es {
* 将点从屏幕坐标转换为世界坐标
* @param screenPosition
*/
public screenToWorldPoint(screenPosition: Vector2): Vector2{
public screenToWorldPoint(screenPosition: Vector2): Vector2 {
this.updateMatrixes();
screenPosition = Vector2.transform(screenPosition, this._inverseTransformMatrix);
return screenPosition;
@@ -376,7 +353,7 @@ module es {
/**
* 返回鼠标在世界空间中的位置
*/
public mouseToWorldPoint(): Vector2{
public mouseToWorldPoint(): Vector2 {
return this.screenToWorldPoint(Input.touchPosition);
}
@@ -476,5 +453,32 @@ module es {
public setCenteredDeadzone(width: number, height: number) {
this.deadzone = new Rectangle((this.bounds.width - width) / 2, (this.bounds.height - height) / 2, width, height);
}
protected updateMatrixes() {
if (!this._areMatrixedDirty)
return;
let tempMat: Matrix2D;
this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y);
if (this._zoom != 1) {
tempMat = Matrix2D.create().scale(this._zoom, this._zoom);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
if (this.entity.transform.rotation != 0) {
tempMat = Matrix2D.create().rotate(this.entity.transform.rotation);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
this._inverseTransformMatrix = this._transformMatrix.invert();
// 无论何时矩阵改变边界都是无效的
this._areBoundsDirty = true;
this._areMatrixedDirty = false;
}
}
}

View File

@@ -1,22 +1,22 @@
module es {
export class ComponentPool<T extends PooledComponent>{
export class ComponentPool<T extends PooledComponent> {
private _cache: T[];
private _type: any;
constructor(typeClass: any){
constructor(typeClass: any) {
this._type = typeClass;
this._cache = [];
}
public obtain(): T{
public obtain(): T {
try {
return this._cache.length > 0 ? this._cache.shift() : new this._type();
} catch(err){
} catch (err) {
throw new Error(this._type + err);
}
}
public free(component: T){
public free(component: T) {
component.reset();
this._cache.push(component);
}

View File

@@ -3,8 +3,8 @@ module es {
* 用于比较组件更新排序
*/
export class IUpdatableComparer {
public compare(a: Component, b: Component){
return a.updateOrder - b.updateOrder;
}
public compare(a: Component, b: Component) {
return a.updateOrder - b.updateOrder;
}
}
}

View File

@@ -3,13 +3,13 @@ module es {
export class Mesh extends RenderableComponent {
private _mesh: egret.Mesh;
constructor(){
constructor() {
super();
this._mesh = new egret.Mesh();
}
public setTexture(texture: egret.Texture): Mesh{
public setTexture(texture: egret.Texture): Mesh {
this._mesh.texture = texture;
return this;

View File

@@ -1,26 +1,10 @@
///<reference path="./Collider.ts" />
module es {
export class BoxCollider extends Collider {
public get width(){
return (this.shape as Box).width;
}
public set width(value: number){
this.setWidth(value);
}
public get height(){
return (this.shape as Box).height;
}
public set height(value: number){
this.setHeight(value);
}
/**
* 零参数构造函数要求RenderableComponent在实体上这样碰撞器可以在实体被添加到场景时调整自身的大小。
*/
constructor(){
constructor() {
super();
// 我们在这里插入一个1x1框作为占位符直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据
@@ -28,15 +12,31 @@ module es {
this._colliderRequiresAutoSizing = true;
}
public get width() {
return (this.shape as Box).width;
}
public set width(value: number) {
this.setWidth(value);
}
public get height() {
return (this.shape as Box).height;
}
public set height(value: number) {
this.setHeight(value);
}
/**
* 设置BoxCollider的大小
* @param width
* @param height
*/
public setSize(width: number, height: number){
public setSize(width: number, height: number) {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width || height != box.height){
if (width != box.width || height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, height);
if (this.entity && this._isParentEntityAddedToScene)
@@ -50,10 +50,10 @@ module es {
* 设置BoxCollider的宽度
* @param width
*/
public setWidth(width: number): BoxCollider{
public setWidth(width: number): BoxCollider {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width){
if (width != box.width) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, box.height);
if (this.entity && this._isParentEntityAddedToScene)
@@ -67,10 +67,10 @@ module es {
* 设置BoxCollider的高度
* @param height
*/
public setHeight(height: number){
public setHeight(height: number) {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (height != box.height){
if (height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(box.width, height);
if (this.entity && this._isParentEntityAddedToScene)
@@ -78,7 +78,7 @@ module es {
}
}
public toString(){
public toString() {
return `[BoxCollider: bounds: ${this.bounds}]`;
}
}

View File

@@ -1,13 +1,5 @@
module es {
export class CircleCollider extends Collider {
public get radius(): number {
return (this.shape as Circle).radius;
}
public set radius(value: number) {
this.setRadius(value);
}
/**
* 创建一个有半径的圆
*
@@ -23,6 +15,14 @@ module es {
this.shape = new Circle(radius ? radius : 1);
}
public get radius(): number {
return (this.shape as Circle).radius;
}
public set radius(value: number) {
this.setRadius(value);
}
/**
* 设置圆的半径
* @param radius

View File

@@ -4,23 +4,40 @@ module es {
* 对撞机的基本形状
*/
public shape: Shape;
/**
* 将localOffset添加到实体。获取碰撞器几何图形的最终位置。
* 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转
* 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件
*/
public get localOffset(): Vector2 {
return this._localOffset;
}
public isTrigger: boolean;
/**
* 将localOffset添加到实体。获取碰撞器几何图形的最终位置。
* 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转
* @param value
* 在处理冲突时physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
public physicsLayer = 1 << 0;
/**
* 碰撞器在使用移动器移动时应该碰撞的层
* 默认为所有层
*/
public collidesWithLayers = Physics.allLayers;
/**
* 如果为true碰撞器将根据附加的变换缩放和旋转
*/
public shouldColliderScaleAndRotateWithTransform = true;
/**
* 这个对撞机在物理系统注册时的边界。
* 存储这个允许我们始终能够安全地从物理系统中移除对撞机,即使它在试图移除它之前已经被移动了。
*/
public registeredPhysicsBounds: Rectangle = new Rectangle();
public _localOffsetLength: number;
public _isPositionDirty: boolean = true;
public _isRotationDirty: boolean = true;
protected _colliderRequiresAutoSizing;
/**
* 标记来跟踪我们的实体是否被添加到场景中
*/
protected _isParentEntityAddedToScene;
/**
* 标记来记录我们是否注册了物理系统
*/
protected _isColliderRegistered;
/**
* 镖师碰撞器的绝对位置
@@ -39,27 +56,8 @@ module es {
return 0;
}
/**
* 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件
*/
public isTrigger: boolean;
/**
* 在处理冲突时physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法
*/
public physicsLayer = 1 << 0;
/**
* 碰撞器在使用移动器移动时应该碰撞的层
* 默认为所有层
*/
public collidesWithLayers = Physics.allLayers;
/**
* 如果为true碰撞器将根据附加的变换缩放和旋转
*/
public shouldColliderScaleAndRotateWithTransform = true;
public get bounds(): Rectangle {
if (this._isPositionDirty || this._isRotationDirty){
if (this._isPositionDirty || this._isRotationDirty) {
this.shape.recalculateBounds(this);
this._isPositionDirty = this._isRotationDirty = false;
}
@@ -67,26 +65,24 @@ module es {
return this.shape.bounds;
}
/**
* 这个对撞机在物理系统注册时的边界。
* 存储这个允许我们始终能够安全地从物理系统中移除对撞机,即使它在试图移除它之前已经被移动了。
*/
public registeredPhysicsBounds: Rectangle = new Rectangle();
protected _colliderRequiresAutoSizing;
protected _localOffset: Vector2 = Vector2.zero;
public _localOffsetLength: number;
/**
* 标记来跟踪我们的实体是否被添加到场景中
* 将localOffset添加到实体。获取碰撞器几何图形的最终位置。
* 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转
*/
protected _isParentEntityAddedToScene;
/**
* 标记来记录我们是否注册了物理系统
*/
protected _isColliderRegistered;
public get localOffset(): Vector2 {
return this._localOffset;
}
public _isPositionDirty: boolean = true;
public _isRotationDirty: boolean = true;
/**
* 将localOffset添加到实体。获取碰撞器几何图形的最终位置。
* 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
/**
* 将localOffset添加到实体。获取碰撞器的最终位置。
@@ -229,7 +225,7 @@ module es {
return didCollide;
}
public clone(): Component{
public clone(): Component {
let collider = ObjectUtils.clone<Collider>(this);
collider.entity = null;

View File

@@ -1,4 +1,4 @@
module es{
module es {
/**
* 当添加到组件时,每当实体上的冲突器与另一个组件重叠/退出时,将调用这些方法。
* ITriggerListener方法将在实现接口的触发器实体上的任何组件上调用。

View File

@@ -9,7 +9,7 @@ module es {
export class Mover extends Component {
private _triggerHelper: ColliderTriggerHelper;
public onAddedToEntity(){
public onAddedToEntity() {
this._triggerHelper = new ColliderTriggerHelper(this.entity);
}
@@ -18,14 +18,14 @@ module es {
* @param motion
* @param collisionResult
*/
public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean{
if (!this.entity.getComponent(Collider) || !this._triggerHelper){
public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean {
if (!this.entity.getComponent(Collider) || !this._triggerHelper) {
return false;
}
// 移动所有的非触发碰撞器并获得最近的碰撞
let colliders: Collider[] = this.entity.getComponents(Collider);
for (let i = 0; i < colliders.length; i ++){
for (let i = 0; i < colliders.length; i++) {
let collider = colliders[i];
// 不检测触发器 在我们移动后会重新访问它
@@ -38,19 +38,19 @@ module es {
bounds.y += motion.y;
let neighbors = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers);
for (let j = 0; j < neighbors.length; j ++){
for (let j = 0; j < neighbors.length; j++) {
let neighbor = neighbors[j];
// 不检测触发器
if (neighbor.isTrigger)
continue;
let _internalcollisionResult: CollisionResult = new CollisionResult();
if (collider.collidesWith(neighbor, motion, _internalcollisionResult)){
if (collider.collidesWith(neighbor, motion, _internalcollisionResult)) {
// 如果碰撞 则退回之前的移动量
motion = motion.subtract(_internalcollisionResult.minimumTranslationVector);
// 如果我们碰到多个对象,为了简单起见,只取第一个。
if (_internalcollisionResult.collider != null){
if (_internalcollisionResult.collider != null) {
collisionResult = _internalcollisionResult;
}
}
@@ -66,7 +66,7 @@ module es {
* 将calculatemomovement应用到实体并更新triggerHelper
* @param motion
*/
public applyMovement(motion: Vector2){
public applyMovement(motion: Vector2) {
// 移动实体到它的新位置,如果我们有一个碰撞,否则移动全部数量。当碰撞发生时,运动被更新
this.entity.position = Vector2.add(this.entity.position, motion);
@@ -80,7 +80,7 @@ module es {
* @param motion
* @param collisionResult
*/
public move(motion: Vector2, collisionResult: CollisionResult){
public move(motion: Vector2, collisionResult: CollisionResult) {
this.calculateMovement(motion, collisionResult);
this.applyMovement(motion);
return collisionResult.collider != null;

View File

@@ -7,7 +7,7 @@ module es {
private _tempTriggerList: ITriggerListener[] = [];
private _collider: Collider;
public onAddedToEntity(){
public onAddedToEntity() {
this._collider = this.entity.getComponent<Collider>(Collider);
if (!this._collider)
console.warn("ProjectileMover has no Collider. ProjectilMover requires a Collider!");
@@ -17,7 +17,7 @@ module es {
* 移动考虑碰撞的实体
* @param motion
*/
public move(motion: Vector2): boolean{
public move(motion: Vector2): boolean {
if (!this._collider)
return false;
@@ -28,9 +28,9 @@ module es {
// 获取任何可能在新位置发生碰撞的东西
let neighbors = Physics.boxcastBroadphase(this._collider.bounds, this._collider.collidesWithLayers);
for (let i = 0; i < neighbors.length; i ++){
for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i];
if (this._collider.overlaps(neighbor) && neighbor.enabled){
if (this._collider.overlaps(neighbor) && neighbor.enabled) {
didCollide = true;
this.notifyTriggerListeners(this._collider, neighbor);
}
@@ -39,17 +39,17 @@ module es {
return didCollide;
}
private notifyTriggerListeners(self: Collider, other: Collider){
private notifyTriggerListeners(self: Collider, other: Collider) {
// 通知我们重叠的碰撞器实体上的任何侦听器
other.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){
for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(self, other);
}
this._tempTriggerList.length = 0;
// 通知此实体上的任何侦听器
this.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){
for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(other, self);
}
this._tempTriggerList.length = 0;

View File

@@ -8,6 +8,12 @@ module es {
* 用于装载egret显示对象
*/
public displayObject: egret.DisplayObject = new egret.DisplayObject();
/**
* 用于着色器处理精灵
*/
public color: number = 0x000000;
protected _areBoundsDirty = true;
/**
* renderableComponent的宽度
* 如果你不重写bounds属性则需要实现这个
@@ -24,11 +30,43 @@ module es {
return this.bounds.height;
}
protected _localOffset: Vector2 = Vector2.zero;
/**
* 从父实体的偏移量。用于向需要特定定位的实体
*/
public get localOffset(): Vector2 {
return this._localOffset;
}
/**
* 从父实体的偏移量。用于向需要特定定位的实体
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
protected _renderLayer: number = 0;
/**
* 较低的渲染层在前面,较高的在后面
*/
public get renderLayer(): number {
return this._renderLayer;
}
public set renderLayer(value: number) {
}
protected _bounds: Rectangle = new Rectangle();
/**
* 这个物体的AABB, 用于相机剔除
*/
public get bounds(): Rectangle {
if (this._areBoundsDirty){
if (this._areBoundsDirty) {
this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, Vector2.zero,
this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height);
this._areBoundsDirty = false;
@@ -37,36 +75,7 @@ module es {
return this._bounds;
}
/**
* 较低的渲染层在前面,较高的在后面
*/
public get renderLayer(): number{
return this._renderLayer;
}
public set renderLayer(value: number){
}
/**
* 用于着色器处理精灵
*/
public color: number = 0x000000;
/**
* 从父实体的偏移量。用于向需要特定定位的实体
*/
public get localOffset(): Vector2{
return this._localOffset;
}
/**
* 从父实体的偏移量。用于向需要特定定位的实体
* @param value
*/
public set localOffset(value: Vector2){
this.setLocalOffset(value);
}
private _isVisible: boolean;
/**
* 可渲染的可见性。状态的改变会调用onBecameVisible/onBecameInvisible方法
@@ -80,7 +89,7 @@ module es {
* @param value
*/
public set isVisible(value: boolean) {
if (this._isVisible != value){
if (this._isVisible != value) {
this._isVisible = value;
if (this._isVisible)
@@ -90,12 +99,6 @@ module es {
}
}
protected _localOffset: Vector2 = Vector2.zero;
protected _renderLayer: number = 0;
protected _bounds: Rectangle = new Rectangle();
private _isVisible: boolean;
protected _areBoundsDirty = true;
public onEntityTransformChanged(comp: transform.Component) {
this._areBoundsDirty = true;
}
@@ -106,22 +109,6 @@ module es {
*/
public abstract render(camera: Camera);
/**
* 当renderableComponent进入相机框架时调用
* 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用
*/
protected onBecameVisible() {
this.displayObject.visible = this.isVisible;
}
/**
* 当renderableComponent离开相机框架时调用
* 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用
*/
protected onBecameInvisible() {
this.displayObject.visible = this.isVisible;
}
/**
* 如果renderableComponent的边界与camera.bounds相交 返回true
* 用于处理isVisible标志的状态开关
@@ -137,8 +124,8 @@ module es {
* 较低的渲染层在前面,较高的在后面
* @param renderLayer
*/
public setRenderLayer(renderLayer: number): RenderableComponent{
if (renderLayer != this._renderLayer){
public setRenderLayer(renderLayer: number): RenderableComponent {
if (renderLayer != this._renderLayer) {
let oldRenderLayer = this._renderLayer;
this._renderLayer = renderLayer;
@@ -154,7 +141,7 @@ module es {
* 用于着色器处理精灵
* @param color
*/
public setColor(color: number): RenderableComponent{
public setColor(color: number): RenderableComponent {
this.color = color;
return this;
}
@@ -163,8 +150,8 @@ module es {
* 从父实体的偏移量。用于向需要特定定位的实体
* @param offset
*/
public setLocalOffset(offset: Vector2): RenderableComponent{
if (this._localOffset != offset){
public setLocalOffset(offset: Vector2): RenderableComponent {
if (this._localOffset != offset) {
this._localOffset = offset;
}
@@ -174,7 +161,7 @@ module es {
/**
* 进行状态同步
*/
public sync(camera: Camera){
public sync(camera: Camera) {
this.displayObject.x = this.entity.position.x + this.localOffset.x - camera.position.x + camera.origin.x;
this.displayObject.y = this.entity.position.y + this.localOffset.y - camera.position.y + camera.origin.y;
this.displayObject.scaleX = this.entity.scale.x;
@@ -182,8 +169,24 @@ module es {
this.displayObject.rotation = this.entity.rotation;
}
public toString(){
public toString() {
return `[RenderableComponent] renderLayer: ${this.renderLayer}`;
}
/**
* 当renderableComponent进入相机框架时调用
* 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用
*/
protected onBecameVisible() {
this.displayObject.visible = this.isVisible;
}
/**
* 当renderableComponent离开相机框架时调用
* 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用
*/
protected onBecameInvisible() {
this.displayObject.visible = this.isVisible;
}
}
}

View File

@@ -6,7 +6,7 @@ module es {
private _scrollX = 0;
private _scrollY = 0;
public update(){
public update() {
this._scrollX += this.scrollSpeedX * Time.deltaTime;
this._scrollY += this.scroolSpeedY * Time.deltaTime;
this.sourceRect.x = this._scrollX;

View File

@@ -3,7 +3,7 @@ module es {
public readonly sprites: Sprite[];
public readonly frameRate: number;
constructor(sprites: Sprite[], frameRate: number){
constructor(sprites: Sprite[], frameRate: number) {
this.sprites = sprites;
this.frameRate = frameRate;
}

View File

@@ -45,6 +45,12 @@ module es {
* 当前动画的精灵数组中当前帧的索引
*/
public currentFrame: number;
public _elapsedTime: number = 0;
public _loopMode: LoopMode;
constructor(sprite?: Sprite) {
super(sprite);
}
/**
* 检查当前动画是否正在运行
@@ -53,19 +59,13 @@ module es {
return this.animationState == State.running;
}
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
/** 提供对可用动画列表的访问 */
public get animations() {
return this._animations;
}
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
public _elapsedTime: number = 0;
public _loopMode: LoopMode;
constructor(sprite?: Sprite) {
super(sprite);
}
public update() {
if (this.animationState != State.running || !this.currentAnimation) return;

View File

@@ -2,6 +2,14 @@ module es {
import Bitmap = egret.Bitmap;
export class SpriteRenderer extends RenderableComponent {
constructor(sprite: Sprite | egret.Texture = null) {
super();
if (sprite instanceof Sprite)
this.setSprite(sprite);
else if (sprite instanceof egret.Texture)
this.setSprite(new Sprite(sprite));
}
public get bounds() {
if (this._areBoundsDirty) {
if (this._sprite) {
@@ -15,21 +23,6 @@ module es {
return this._bounds;
}
/**
* 精灵的原点。这是在设置精灵时自动设置的
*/
public get origin(): Vector2 {
return this._origin;
}
/**
* 精灵的原点。这是在设置精灵时自动设置的
* @param value
*/
public set origin(value: Vector2) {
this.setOrigin(value);
}
/**
* 用归一化方法设置原点
* x/y 均为 0-1
@@ -49,6 +42,25 @@ module es {
value.y * this.height / this.entity.transform.scale.y));
}
protected _origin: Vector2;
/**
* 精灵的原点。这是在设置精灵时自动设置的
*/
public get origin(): Vector2 {
return this._origin;
}
/**
* 精灵的原点。这是在设置精灵时自动设置的
* @param value
*/
public set origin(value: Vector2) {
this.setOrigin(value);
}
protected _sprite: Sprite;
/**
* 应该由这个精灵显示的精灵
* 当设置时精灵的原点也被设置为精灵的origin
@@ -66,17 +78,6 @@ module es {
this.setSprite(value);
}
protected _origin: Vector2;
protected _sprite: Sprite;
constructor(sprite: Sprite | egret.Texture = null) {
super();
if (sprite instanceof Sprite)
this.setSprite(sprite);
else if (sprite instanceof egret.Texture)
this.setSprite(new Sprite(sprite));
}
/**
* 设置精灵并更新精灵的原点以匹配sprite.origin
* @param sprite

View File

@@ -8,19 +8,6 @@ module es {
protected leftTexture: egret.Bitmap;
protected rightTexture: egret.Bitmap;
public get scrollX() {
return this.sourceRect.x;
}
public set scrollX(value: number) {
this.sourceRect.x = value;
}
public get scrollY() {
return this.sourceRect.y;
}
public set scrollY(value: number) {
this.sourceRect.y = value;
}
constructor(sprite: Sprite) {
super(sprite);
@@ -33,6 +20,22 @@ module es {
this.sourceRect = sprite.sourceRect;
}
public get scrollX() {
return this.sourceRect.x;
}
public set scrollX(value: number) {
this.sourceRect.x = value;
}
public get scrollY() {
return this.sourceRect.y;
}
public set scrollY(value: number) {
this.sourceRect.y = value;
}
public render(camera: es.Camera) {
if (!this.sprite)
return;

View File

@@ -15,20 +15,10 @@ module es {
* 全局内容管理器加载任何应该停留在场景之间的资产
*/
public static content: ContentManager;
/**
* 提供对单例/游戏实例的访问
* @constructor
*/
public static get Instance(){
return this._instance;
}
/**
* 简化对内部类的全局内容实例的访问
*/
public static _instance: Core;
public _scene: Scene;
public _nextScene: Scene;
public _sceneTransition: SceneTransition;
/**
@@ -36,6 +26,26 @@ module es {
*/
public _globalManagers: GlobalManager[] = [];
constructor() {
super();
Core._instance = this;
Core.emitter = new Emitter<CoreEvents>();
Core.content = new ContentManager();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
/**
* 提供对单例/游戏实例的访问
* @constructor
*/
public static get Instance() {
return this._instance;
}
public _scene: Scene;
/**
* 当前活动的场景。注意,如果设置了该设置,在更新结束之前场景实际上不会改变
*/
@@ -50,7 +60,7 @@ module es {
* @param value
*/
public static set scene(value: Scene) {
if (!value){
if (!value) {
console.error("场景不能为空");
return;
}
@@ -65,39 +75,106 @@ module es {
}
}
constructor() {
super();
/**
* 临时运行SceneTransition允许一个场景过渡到另一个平滑的自定义效果。
* @param sceneTransition
*/
public static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T {
if (this._instance._sceneTransition) {
console.warn("在前一个场景完成之前,不能开始一个新的场景转换。");
return;
}
Core._instance = this;
Core.emitter = new Emitter<CoreEvents>();
Core.content = new ContentManager();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
this._instance._sceneTransition = sceneTransition;
return sceneTransition;
}
private onAddToStage(){
Core.graphicsDevice = new GraphicsDevice();
this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this);
this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this);
this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
Input.initialize();
this.initialize();
/**
* 添加一个全局管理器对象,它的更新方法将调用场景前的每一帧。
* @param manager
*/
public static registerGlobalManager(manager: es.GlobalManager) {
this._instance._globalManagers.push(manager);
manager.enabled = true;
}
public onOrientationChanged(){
/**
* 删除全局管理器对象
* @param manager
*/
public static unregisterGlobalManager(manager: es.GlobalManager) {
this._instance._globalManagers.remove(manager);
manager.enabled = false;
}
/**
* 获取类型为T的全局管理器
* @param type
*/
public static getGlobalManager<T extends es.GlobalManager>(type): T {
for (let i = 0; i < this._instance._globalManagers.length; i++) {
if (this._instance._globalManagers[i] instanceof type)
return this._instance._globalManagers[i] as T;
}
return null;
}
public onOrientationChanged() {
Core.emitter.emit(CoreEvents.OrientationChanged);
}
public async draw() {
if (this._sceneTransition) {
this._sceneTransition.preRender();
// 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景
if (this._scene && !this._sceneTransition.hasPreviousSceneRender) {
this._scene.render();
this._scene.postRender();
await this._sceneTransition.onBeginTransition();
} else if (this._sceneTransition) {
if (this._scene && this._sceneTransition.isNewSceneLoaded) {
this._scene.render();
this._scene.postRender();
}
this._sceneTransition.render();
}
} else if (this._scene) {
this._scene.render();
Debug.render();
// 如果我们没有一个活跃的场景转换,就像平常一样渲染
this._scene.postRender();
}
}
public startDebugUpdate() {
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
}
public endDebugUpdate() {
TimeRuler.Instance.endMark("update");
}
/**
* 在一个场景结束后,下一个场景开始之前调用
*/
public onSceneChanged() {
Core.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged();
}
/**
* 当屏幕大小发生改变时调用
*/
protected onGraphicsDeviceReset(){
protected onGraphicsDeviceReset() {
Core.emitter.emit(CoreEvents.GraphicsDeviceReset);
}
protected initialize(){
protected initialize() {
}
protected async update() {
@@ -139,92 +216,15 @@ module es {
await this.draw();
}
public async draw() {
if (this._sceneTransition){
this._sceneTransition.preRender();
private onAddToStage() {
Core.graphicsDevice = new GraphicsDevice();
// 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景
if (this._scene && !this._sceneTransition.hasPreviousSceneRender){
this._scene.render();
this._scene.postRender();
await this._sceneTransition.onBeginTransition();
} else if (this._sceneTransition) {
if (this._scene && this._sceneTransition.isNewSceneLoaded) {
this._scene.render();
this._scene.postRender();
}
this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this);
this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this);
this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
this._sceneTransition.render();
}
} else if (this._scene) {
this._scene.render();
Debug.render();
// 如果我们没有一个活跃的场景转换,就像平常一样渲染
this._scene.postRender();
}
}
public startDebugUpdate(){
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
}
public endDebugUpdate(){
TimeRuler.Instance.endMark("update");
}
/**
* 在一个场景结束后,下一个场景开始之前调用
*/
public onSceneChanged(){
Core.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged();
}
/**
* 临时运行SceneTransition允许一个场景过渡到另一个平滑的自定义效果。
* @param sceneTransition
*/
public static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T {
if (this._instance._sceneTransition) {
console.warn("在前一个场景完成之前,不能开始一个新的场景转换。");
return;
}
this._instance._sceneTransition = sceneTransition;
return sceneTransition;
}
/**
* 添加一个全局管理器对象,它的更新方法将调用场景前的每一帧。
* @param manager
*/
public static registerGlobalManager(manager: es.GlobalManager){
this._instance._globalManagers.push(manager);
manager.enabled = true;
}
/**
* 删除全局管理器对象
* @param manager
*/
public static unregisterGlobalManager(manager: es.GlobalManager){
this._instance._globalManagers.remove(manager);
manager.enabled = false;
}
/**
* 获取类型为T的全局管理器
* @param type
*/
public static getGlobalManager<T extends es.GlobalManager>(type): T {
for (let i = 0; i < this._instance._globalManagers.length; i ++){
if (this._instance._globalManagers[i] instanceof type)
return this._instance._globalManagers[i] as T;
}
return null;
Input.initialize();
this.initialize();
}
}
}

View File

@@ -1,5 +1,5 @@
module es {
export enum CoreEvents{
export enum CoreEvents {
/**
* 在图形设备重置时触发。当这种情况发生时任何渲染目标或其他内容的VRAM将被擦除需要重新生成
*/

View File

@@ -22,6 +22,31 @@ module es {
* 当前附加到此实体的所有组件的列表
*/
public readonly components: ComponentList;
/**
* 指定应该调用这个entity update方法的频率。1表示每一帧2表示每一帧以此类推
*/
public updateInterval: number = 1;
public componentBits: BitSet;
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 _isDestroyed: boolean;
/**
* 如果调用了destroy那么在下一次处理实体之前这将一直为true
*/
public get isDestroyed() {
return this._isDestroyed;
}
private _tag: number = 0;
/**
* 你可以随意使用。稍后可以使用它来查询场景中具有特定标记的所有实体
@@ -38,10 +63,7 @@ module es {
this.setTag(value);
}
/**
* 指定应该调用这个entity update方法的频率。1表示每一帧2表示每一帧以此类推
*/
public updateInterval: number = 1;
private _enabled: boolean = true;
/**
* 启用/禁用实体。当禁用碰撞器从物理系统和组件中移除时,方法将不会被调用
@@ -58,6 +80,8 @@ module es {
this.setEnabled(value);
}
private _updateOrder: number = 0;
/**
* 更新此实体的顺序。updateOrder还用于对scene.entities上的标签列表进行排序
*/
@@ -73,20 +97,6 @@ module es {
this.setUpdateOrder(value);
}
public _isDestroyed: boolean;
/**
* 如果调用了destroy那么在下一次处理实体之前这将一直为true
*/
public get isDestroyed() {
return this._isDestroyed;
}
public componentBits: BitSet;
private _tag: number = 0;
private _enabled: boolean = true;
private _updateOrder: number = 0;
public get parent(): Transform {
return this.transform.parent;
}
@@ -111,7 +121,7 @@ module es {
return this.transform.localPosition;
}
public set localPosition(value: Vector2){
public set localPosition(value: Vector2) {
this.transform.setLocalPosition(value);
}
@@ -127,7 +137,7 @@ module es {
return this.transform.rotationDegrees;
}
public set rotationDegrees(value: number){
public set rotationDegrees(value: number) {
this.transform.setRotationDegrees(value);
}
@@ -135,7 +145,7 @@ module es {
return this.transform.localRotation;
}
public set localRotation(value: number){
public set localRotation(value: number) {
this.transform.setLocalRotation(value);
}
@@ -143,7 +153,7 @@ module es {
return this.transform.localRotationDegrees;
}
public set localRotationDegrees(value: number){
public set localRotationDegrees(value: number) {
this.transform.setLocalRotationDegrees(value);
}
@@ -159,7 +169,7 @@ module es {
return this.transform.localScale;
}
public set localScale(value: Vector2){
public set localScale(value: Vector2) {
this.transform.setLocalScale(value);
}
@@ -175,15 +185,6 @@ module es {
return this.transform.worldToLocalTransform;
}
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);
@@ -293,32 +294,6 @@ module es {
return entity;
}
/**
* 将实体的属性、组件和碰撞器复制到此实例
* @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;
}
}
/**
* 在提交了所有挂起的实体更改后,将此实体添加到场景时调用
*/
@@ -431,5 +406,31 @@ module es {
public toString(): string {
return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`;
}
/**
* 将实体的属性、组件和碰撞器复制到此实例
* @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;
}
}
}
}

View File

@@ -1,350 +1,355 @@
module es {
/** 场景 */
export class Scene extends egret.DisplayObjectContainer {
/**
* 默认场景摄像机
*/
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;
/** 场景 */
export class Scene extends egret.DisplayObjectContainer {
/**
* 默认场景摄像机
*/
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;
public _renderers: Renderer[] = [];
public readonly _postProcessors: PostProcessor[] = [];
public _didSceneBegin;
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.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager();
constructor() {
super();
this.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager();
this.entityProcessors = new EntityProcessorList();
this.entityProcessors = new EntityProcessorList();
this.initialize();
}
this.initialize();
}
/**
* 辅助器创建一个场景与DefaultRenderer附加并准备使用
*/
public static createWithDefaultRenderer() {
let scene = new Scene();
scene.addRenderer(new DefaultRenderer());
return scene;
}
/**
* 在场景子类中重写这个并在这里进行加载。在场景设置好之后在调用begin之前从构造器中调用。
*/
public initialize(){}
/**
* 在场景子类中重写这个并在这里进行加载。在场景设置好之后在调用begin之前从构造器中调用。
*/
public initialize() {
}
/**
* 在场景子类中重写这个。当SceneManager将此场景设置为活动场景时将调用此操作。
*/
public async onStart() {}
/**
* 在场景子类中重写这个。当SceneManager将此场景设置为活动场景时将调用此操作。
*/
public async onStart() {
}
/**
* 在场景子类中重写这个并在这里做任何必要的卸载。当SceneManager从活动槽中删除此场景时调用。
*/
public unload() { }
/**
* 在场景子类中重写这个并在这里做任何必要的卸载。当SceneManager从活动槽中删除此场景时调用。
*/
public unload() {
}
/**
* 在场景子类中重写这个,当该场景当获得焦点时调用
*/
public onActive() {}
/**
* 在场景子类中重写这个,当该场景当获得焦点时调用
*/
public onActive() {
}
/**
* 在场景子类中重写这个,当该场景当失去焦点时调用
*/
public onDeactive() {}
/**
* 在场景子类中重写这个,当该场景当失去焦点时调用
*/
public onDeactive() {
}
public async begin() {
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();
}
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();
}
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 async begin() {
if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
}
}
/**
* 为场景添加一个渲染器
* @param renderer
*/
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
renderer.onAddedToScene(this);
Physics.reset();
return renderer;
}
if (this.entityProcessors)
this.entityProcessors.begin();
/**
* 获取类型为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;
}
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);
return null;
}
this._didSceneBegin = true;
this.onStart();
}
/**
* 从场景中移除渲染器
* @param renderer
*/
public removeRenderer(renderer: Renderer) {
if (!this._renderers.contains(renderer))
return;
this._renderers.remove(renderer);
renderer.unload();
}
public end() {
this._didSceneBegin = false;
/**
* 添加一个后处理器到场景。设置场景字段并调用后处理器。onAddedToScene使后处理器可以使用场景ContentManager加载资源。
* @param postProcessor
*/
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this);
if (this._didSceneBegin){
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
}
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].unload();
}
return postProcessor;
}
for (let i = 0; i < this._postProcessors.length; i++) {
this._postProcessors[i].unload();
}
/**
* 获取类型为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;
}
this.entities.removeAllEntities();
this.removeChildren();
return null;
}
this.camera = null;
this.content.dispose();
/**
* 删除一个后处理程序。注意在删除时不会调用unload因此如果不再需要PostProcessor请确保调用unload来释放资源。
* @param postProcessor
*/
public removePostProcessor(postProcessor: PostProcessor){
if (!this._postProcessors.contains(postProcessor))
return;
if (this.entityProcessors)
this.entityProcessors.end();
this._postProcessors.remove(postProcessor);
postProcessor.unload();
}
if (this.parent)
this.parent.removeChild(this);
/**
* 将实体添加到此场景,并返回它
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name);
return this.addEntity(entity);
}
this.unload();
}
/**
* 在场景的实体列表中添加一个实体
* @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;
public update() {
// 更新我们的列表,以防它们有任何变化
this.entities.updateLists();
for (let i = 0; i < entity.transform.childCount; i++)
this.addEntity(entity.transform.getChild(i).entity);
// 更新我们的实体解析器
if (this.entityProcessors)
this.entityProcessors.update();
return entity;
}
// 更新我们的实体组
this.entities.update();
/**
* 从场景中删除所有实体
*/
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
if (this.entityProcessors)
this.entityProcessors.lateUpdate();
/**
* 搜索并返回第一个具有名称的实体
* @param name
*/
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
}
// 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新
this.renderableComponents.updateList();
}
/**
* 返回具有给定标记的所有实体
* @param tag
*/
public findEntitiesWithTag(tag: number): Entity[]{
return this.entities.entitiesWithTag(tag);
}
public render() {
if (this._renderers.length == 0) {
console.error("there are no renderers in the scene!");
return;
}
/**
* 返回类型为T的所有实体
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[]{
return this.entities.entitiesOfType<T>(type);
}
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].render(this);
}
}
/**
* 返回第一个启用加载的类型为T的组件
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
return this.entities.findComponentOfType<T>(type);
}
/**
* 现在的任何后处理器都要完成它的处理
* 只有在SceneTransition请求渲染时它才会有一个值。
*/
public postRender() {
if (this.enablePostProcessing) {
for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enabled) {
this._postProcessors[i].process();
}
}
}
}
/**
* 返回类型为T的所有已启用已加载组件的列表
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[] {
return this.entities.findComponentsOfType<T>(type);
}
/**
* 为场景添加一个渲染器
* @param renderer
*/
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
/**
* 在场景中添加一个EntitySystem处理器
* @param processor 处理器
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
renderer.onAddedToScene(this);
/**
* 从场景中删除EntitySystem处理器
* @param processor
*/
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
return renderer;
}
/**
* 获取EntitySystem处理
*/
public getEntityProcessor<T extends EntitySystem>(): T {
return this.entityProcessors.getProcessor<T>();
}
}
/**
* 获取类型为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;
}
/**
* 删除一个后处理程序。注意在删除时不会调用unload因此如果不再需要PostProcessor请确保调用unload来释放资源。
* @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>();
}
}
}

View File

@@ -1,80 +1,82 @@
module es {
export class EntitySystem {
private _scene: Scene;
private _entities: Entity[] = [];
private _matcher: Matcher;
public get matcher(){
return this._matcher;
constructor(matcher?: Matcher) {
this._matcher = matcher ? matcher : Matcher.empty();
}
public get scene(){
private _scene: Scene;
public get scene() {
return this._scene;
}
public set scene(value: Scene){
public set scene(value: Scene) {
this._scene = value;
this._entities = [];
}
constructor(matcher?: Matcher){
this._matcher = matcher ? matcher : Matcher.empty();
private _matcher: Matcher;
public get matcher() {
return this._matcher;
}
public initialize(){
public initialize() {
}
public onChanged(entity: Entity){
public onChanged(entity: Entity) {
let contains = this._entities.contains(entity);
let interest = this._matcher.IsIntersted(entity);
if (interest && !contains)
this.add(entity);
else if(!interest && contains)
else if (!interest && contains)
this.remove(entity);
}
public add(entity: Entity){
public add(entity: Entity) {
this._entities.push(entity);
this.onAdded(entity);
}
public onAdded(entity: Entity){
public onAdded(entity: Entity) {
}
public remove(entity: Entity){
public remove(entity: Entity) {
this._entities.remove(entity);
this.onRemoved(entity);
}
public onRemoved(entity: Entity){
public onRemoved(entity: Entity) {
}
public update(){
public update() {
this.begin();
this.process(this._entities);
}
public lateUpdate(){
public lateUpdate() {
this.lateProcess(this._entities);
this.end();
}
protected begin(){
protected begin() {
}
protected process(entities: Entity[]){
protected process(entities: Entity[]) {
}
protected lateProcess(entities: Entity[]){
protected lateProcess(entities: Entity[]) {
}
protected end(){
protected end() {
}
}

View File

@@ -1,10 +1,10 @@
module es {
export abstract class PassiveSystem extends EntitySystem {
public onChanged(entity: Entity){
public onChanged(entity: Entity) {
}
protected process(entities: Entity[]){
protected process(entities: Entity[]) {
// 我们用我们自己的不考虑实体的基本实体系统来代替
this.begin();
this.end();

View File

@@ -1,17 +1,17 @@
/** 用于协调其他系统的通用系统基类 */
module es {
export abstract class ProcessingSystem extends EntitySystem {
public onChanged(entity: Entity){
public onChanged(entity: Entity) {
}
protected process(entities: Entity[]){
this.begin();
this.processSystem();
this.end();
}
/** 处理我们的系统 每帧调用 */
public abstract processSystem();
protected process(entities: Entity[]) {
this.begin();
this.processSystem();
this.end();
}
}
}

View File

@@ -19,6 +19,78 @@ module es {
export class Transform extends HashObject {
/** 与此转换关联的实体 */
public readonly entity: Entity;
public hierarchyDirty: DirtyType;
public _localDirty: boolean;
public _localPositionDirty: boolean;
public _localScaleDirty: boolean;
public _localRotationDirty: boolean;
public _positionDirty: boolean;
public _worldToLocalDirty: boolean;
public _worldInverseDirty: boolean;
/**
* 值会根据位置、旋转和比例自动重新计算
*/
public _localTransform: Matrix2D = Matrix2D.create();
/**
* 值将自动从本地和父矩阵重新计算。
*/
public _worldTransform = Matrix2D.create().identity();
public _rotationMatrix: Matrix2D = Matrix2D.create();
public _translationMatrix: Matrix2D = Matrix2D.create();
public _scaleMatrix: Matrix2D = Matrix2D.create();
public _children: Transform[];
constructor(entity: Entity) {
super();
this.entity = entity;
this.scale = Vector2.one;
this._children = [];
}
/**
* 这个转换的所有子元素
*/
public get childCount() {
return this._children.length;
}
/**
* 变换在世界空间的旋转度
*/
public get rotationDegrees(): number {
return MathHelper.toDegrees(this._rotation);
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotationDegrees(value: number) {
this.setRotation(MathHelper.toRadians(value));
}
/**
* 旋转相对于父变换旋转的角度
*/
public get localRotationDegrees(): number {
return MathHelper.toDegrees(this._localRotation);
}
/**
* 旋转相对于父变换旋转的角度
* @param value
*/
public set localRotationDegrees(value: number) {
this.localRotation = MathHelper.toRadians(value);
}
public get localToWorldTransform(): Matrix2D {
this.updateTransform();
return this._worldTransform;
}
public _parent: Transform;
/**
* 获取此转换的父转换
*/
@@ -34,22 +106,46 @@ module es {
this.setParent(value);
}
/**
* 这个转换的所有子元素
*/
public get childCount() {
return this._children.length;
public _worldToLocalTransform = Matrix2D.create().identity();
public get worldToLocalTransform(): Matrix2D {
if (this._worldToLocalDirty) {
if (!this.parent) {
this._worldToLocalTransform = Matrix2D.create().identity();
} else {
this.parent.updateTransform();
this._worldToLocalTransform = this.parent._worldTransform.invert();
}
this._worldToLocalDirty = false;
}
return this._worldToLocalTransform;
}
public _worldInverseTransform = Matrix2D.create().identity();
public get worldInverseTransform(): Matrix2D {
this.updateTransform();
if (this._worldInverseDirty) {
this._worldInverseTransform = this._worldTransform.invert();
this._worldInverseDirty = false;
}
return this._worldInverseTransform;
}
public _position: Vector2 = Vector2.zero;
/**
* 变换在世界空间中的位置
*/
public get position(): Vector2 {
this.updateTransform();
if (this._positionDirty){
if (!this.parent){
if (this._positionDirty) {
if (!this.parent) {
this._position = this._localPosition;
}else{
} else {
this.parent.updateTransform();
this._position = Vector2Ext.transformR(this._localPosition, this.parent._worldTransform);
}
@@ -64,10 +160,48 @@ module es {
* 变换在世界空间中的位置
* @param value
*/
public set position(value: Vector2){
public set position(value: Vector2) {
this.setPosition(value.x, value.y);
}
public _scale: Vector2 = Vector2.one;
/**
* 变换在世界空间的缩放
*/
public get scale(): Vector2 {
this.updateTransform();
return this._scale;
}
/**
* 变换在世界空间的缩放
* @param value
*/
public set scale(value: Vector2) {
this.setScale(value);
}
public _rotation: number = 0;
/**
* 在世界空间中以弧度旋转的变换
*/
public get rotation(): number {
this.updateTransform();
return this._rotation;
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotation(value: number) {
this.setRotation(value);
}
public _localPosition: Vector2 = Vector2.zero;
/**
* 转换相对于父转换的位置。如果转换没有父元素则与transform.position相同
*/
@@ -80,87 +214,11 @@ module es {
* 转换相对于父转换的位置。如果转换没有父元素则与transform.position相同
* @param value
*/
public set localPosition(value: Vector2){
public set localPosition(value: Vector2) {
this.setLocalPosition(value);
}
/**
* 在世界空间中以弧度旋转的变换
*/
public get rotation(): number {
this.updateTransform();
return this._rotation;
}
/**
* 变换在世界空间的旋转度
*/
public get rotationDegrees(): number {
return MathHelper.toDegrees(this._rotation);
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotationDegrees(value: number){
this.setRotation(MathHelper.toRadians(value));
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotation(value: number){
this.setRotation(value);
}
/**
* 相对于父变换的旋转变换的旋转。如果转换没有父元素则与transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
/**
* 相对于父变换的旋转变换的旋转。如果转换没有父元素则与transform.rotation相同
* @param value
*/
public set localRotation(value: number){
this.setLocalRotation(value);
}
/**
* 旋转相对于父变换旋转的角度
*/
public get localRotationDegrees(): number {
return MathHelper.toDegrees(this._localRotation);
}
/**
* 旋转相对于父变换旋转的角度
* @param value
*/
public set localRotationDegrees(value: number){
this.localRotation = MathHelper.toRadians(value);
}
/**
* 变换在世界空间的缩放
*/
public get scale(): Vector2{
this.updateTransform();
return this._scale;
}
/**
* 变换在世界空间的缩放
* @param value
*/
public set scale(value: Vector2){
this.setScale(value);
}
public _localScale: Vector2 = Vector2.one;
/**
* 转换相对于父元素的比例。如果转换没有父元素则与transform.scale相同
@@ -174,81 +232,26 @@ module es {
* 转换相对于父元素的比例。如果转换没有父元素则与transform.scale相同
* @param value
*/
public set localScale(value: Vector2){
public set localScale(value: Vector2) {
this.setLocalScale(value);
}
public get worldInverseTransform(): Matrix2D {
this.updateTransform();
if (this._worldInverseDirty){
this._worldInverseTransform = this._worldTransform.invert();
this._worldInverseDirty = false;
}
return this._worldInverseTransform;
}
public get localToWorldTransform(): Matrix2D {
this.updateTransform();
return this._worldTransform;
}
public get worldToLocalTransform(): Matrix2D {
if (this._worldToLocalDirty){
if (!this.parent){
this._worldToLocalTransform = Matrix2D.create().identity();
}else{
this.parent.updateTransform();
this._worldToLocalTransform = this.parent._worldTransform.invert();
}
this._worldToLocalDirty = false;
}
return this._worldToLocalTransform;
}
public _parent: Transform;
public hierarchyDirty: DirtyType;
public _localDirty: boolean;
public _localPositionDirty: boolean;
public _localScaleDirty: boolean;
public _localRotationDirty: boolean;
public _positionDirty: boolean;
public _worldToLocalDirty: boolean;
public _worldInverseDirty: boolean;
/**
* 值会根据位置、旋转和比例自动重新计算
*/
public _localTransform: Matrix2D = Matrix2D.create();
/**
* 值将自动从本地和父矩阵重新计算。
*/
public _worldTransform = Matrix2D.create().identity();
public _worldToLocalTransform = Matrix2D.create().identity();
public _worldInverseTransform = Matrix2D.create().identity();
public _rotationMatrix: Matrix2D = Matrix2D.create();
public _translationMatrix: Matrix2D = Matrix2D.create();
public _scaleMatrix: Matrix2D = Matrix2D.create();
public _position: Vector2 = Vector2.zero;
public _scale: Vector2 = Vector2.one;
public _rotation: number = 0;
public _localPosition: Vector2 = Vector2.zero;
public _localScale: Vector2 = Vector2.one;
public _localRotation: number = 0;
public _children: Transform[];
/**
* 相对于父变换的旋转变换的旋转。如果转换没有父元素则与transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
constructor(entity: Entity) {
super();
this.entity = entity;
this.scale = Vector2.one;
this._children = [];
/**
* 相对于父变换的旋转变换的旋转。如果转换没有父元素则与transform.rotation相同
* @param value
*/
public set localRotation(value: number) {
this.setLocalRotation(value);
}
/**
@@ -289,7 +292,7 @@ module es {
return this;
this._position = position;
if (this.parent){
if (this.parent) {
this.localPosition = Vector2Ext.transformR(this._position, this._worldToLocalTransform);
} else {
this.localPosition = position;
@@ -321,7 +324,7 @@ module es {
*/
public setRotation(radians: number): Transform {
this._rotation = radians;
if (this.parent){
if (this.parent) {
this.localRotation = this.parent.rotation + radians;
} else {
this.localRotation = radians;
@@ -352,7 +355,7 @@ module es {
* 相对于父变换的旋转设置变换的旋转。如果转换没有父元素则与transform.rotation相同
* @param radians
*/
public setLocalRotation(radians: number){
public setLocalRotation(radians: number) {
this._localRotation = radians;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.rotationDirty);
@@ -374,9 +377,9 @@ module es {
*/
public setScale(scale: Vector2): Transform {
this._scale = scale;
if (this.parent){
if (this.parent) {
this.localScale = Vector2.divide(scale, this.parent._scale);
}else{
} else {
this.localScale = scale;
}
return this;
@@ -401,23 +404,23 @@ module es {
this.position = this._position.round();
}
public updateTransform(){
if (this.hierarchyDirty != DirtyType.clean){
public updateTransform() {
if (this.hierarchyDirty != DirtyType.clean) {
if (this.parent)
this.parent.updateTransform();
if (this._localDirty){
if (this._localPositionDirty){
if (this._localDirty) {
if (this._localPositionDirty) {
this._translationMatrix = Matrix2D.create().translate(this._localPosition.x, this._localPosition.y);
this._localPositionDirty = false;
}
if (this._localRotationDirty){
if (this._localRotationDirty) {
this._rotationMatrix = Matrix2D.create().rotate(this._localRotation);
this._localRotationDirty = false;
}
if (this._localScaleDirty){
if (this._localScaleDirty) {
this._scaleMatrix = Matrix2D.create().scale(this._localScale.x, this._localScale.y);
this._localScaleDirty = false;
}
@@ -425,7 +428,7 @@ module es {
this._localTransform = this._scaleMatrix.multiply(this._rotationMatrix);
this._localTransform = this._localTransform.multiply(this._translationMatrix);
if (!this.parent){
if (!this.parent) {
this._worldTransform = this._localTransform;
this._rotation = this._localRotation;
this._scale = this._localScale;
@@ -435,7 +438,7 @@ module es {
this._localDirty = false;
}
if (this.parent){
if (this.parent) {
this._worldTransform = this._localTransform.multiply(this.parent._worldTransform);
this._rotation = this._localRotation + this.parent._rotation;
@@ -449,8 +452,8 @@ module es {
}
}
public setDirty(dirtyFlagType: DirtyType){
if ((this.hierarchyDirty & dirtyFlagType) == 0){
public setDirty(dirtyFlagType: DirtyType) {
if ((this.hierarchyDirty & dirtyFlagType) == 0) {
this.hierarchyDirty |= dirtyFlagType;
switch (dirtyFlagType) {
@@ -469,7 +472,7 @@ module es {
this._children = [];
// 告诉子项发生了变换
for (let i = 0; i < this._children.length; i ++)
for (let i = 0; i < this._children.length; i++)
this._children[i].setDirty(dirtyFlagType);
}
}
@@ -491,13 +494,13 @@ module es {
this.setDirty(DirtyType.scaleDirty);
}
public toString(): string{
public toString(): string {
return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation},
scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation},
localScale: ${this._localScale}]`;
}
public equals(other: Transform){
public equals(other: Transform) {
return other.hashCode == this.hashCode;
}
}

View File

@@ -4,43 +4,43 @@ module es {
*
* 它是由一个位向量实现的,但同样可以把它看成是一个非负整数的集合;集合中的每个整数由对应索引处的集合位表示。该结构的大小由集合中的最大整数决定。
*/
export class BitSet{
export class BitSet {
private static LONG_MASK: number = 0x3f;
private _bits: number[];
constructor(nbits: number = 64){
constructor(nbits: number = 64) {
let length = nbits >> 6;
if ((nbits & BitSet.LONG_MASK) != 0)
length ++;
length++;
this._bits = new Array(length);
}
public and(bs: BitSet){
public and(bs: BitSet) {
let max = Math.min(this._bits.length, bs._bits.length);
let i;
for (let i = 0; i < max; ++i)
this._bits[i] &= bs._bits[i];
while (i < this._bits.length)
this._bits[i ++] = 0;
this._bits[i++] = 0;
}
public andNot(bs: BitSet){
public andNot(bs: BitSet) {
let i = Math.min(this._bits.length, bs._bits.length);
while(--i >= 0)
while (--i >= 0)
this._bits[i] &= ~bs._bits[i];
}
public cardinality(): number{
public cardinality(): number {
let card = 0;
for (let i = this._bits.length - 1; i >= 0; i --){
for (let i = this._bits.length - 1; i >= 0; i--) {
let a = this._bits[i];
if (a == 0)
continue;
if (a == -1){
if (a == -1) {
card += 64;
continue;
}
@@ -56,26 +56,18 @@ module es {
return card;
}
public clear(pos?: number){
if (pos != undefined){
public clear(pos?: number) {
if (pos != undefined) {
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] &= ~(1 << pos);
}else{
for (let i = 0; i < this._bits.length; i ++)
} else {
for (let i = 0; i < this._bits.length; i++)
this._bits[i] = 0;
}
}
private ensure(lastElt: number){
if (lastElt >= this._bits.length){
let nd = new Number[lastElt + 1];
nd = this._bits.copyWithin(0, 0, this._bits.length);
this._bits = nd;
}
}
public get(pos: number): boolean{
public get(pos: number): boolean {
let offset = pos >> 6;
if (offset >= this._bits.length)
return false;
@@ -83,9 +75,9 @@ module es {
return (this._bits[offset] & (1 << pos)) != 0;
}
public intersects(set: BitSet){
public intersects(set: BitSet) {
let i = Math.min(this._bits.length, set._bits.length);
while (--i >= 0){
while (--i >= 0) {
if ((this._bits[i] & set._bits[i]) != 0)
return true;
}
@@ -93,8 +85,8 @@ module es {
return false;
}
public isEmpty(): boolean{
for (let i = this._bits.length - 1; i >= 0; i --){
public isEmpty(): boolean {
for (let i = this._bits.length - 1; i >= 0; i--) {
if (this._bits[i])
return false;
}
@@ -102,34 +94,42 @@ module es {
return true;
}
public nextSetBit(from: number){
public nextSetBit(from: number) {
let offset = from >> 6;
let mask = 1 << from;
while (offset < this._bits.length){
while (offset < this._bits.length) {
let h = this._bits[offset];
do {
if ((h & mask) != 0)
return from;
mask <<= 1;
from ++;
from++;
} while (mask != 0);
mask = 1;
offset ++;
offset++;
}
return -1;
}
public set(pos: number, value: boolean = true){
if (value){
public set(pos: number, value: boolean = true) {
if (value) {
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] |= 1 << pos;
}else{
} else {
this.clear(pos);
}
}
private ensure(lastElt: number) {
if (lastElt >= this._bits.length) {
let nd = new Number[lastElt + 1];
nd = this._bits.copyWithin(0, 0, this._bits.length);
this._bits = nd;
}
}
}
}

View File

@@ -37,7 +37,7 @@ module es {
return this._components;
}
public markEntityListUnsorted(){
public markEntityListUnsorted() {
this._isComponentListUnsorted = true;
}
@@ -76,7 +76,7 @@ module es {
let component = this._components[i];
// 处理渲染层列表
if (component instanceof RenderableComponent){
if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component);
}
@@ -91,7 +91,7 @@ module es {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (component instanceof RenderableComponent){
if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component);
}
@@ -117,7 +117,7 @@ module es {
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){
if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component);
}
@@ -148,7 +148,7 @@ module es {
this._tempBufferList.length = 0;
}
if (this._isComponentListUnsorted){
if (this._isComponentListUnsorted) {
this._components.sort(ComponentList.compareUpdatableOrder.compare);
this._isComponentListUnsorted = false;
}
@@ -156,7 +156,7 @@ module es {
public handleRemove(component: Component) {
// 处理渲染层列表
if (component instanceof RenderableComponent){
if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component);
}

View File

@@ -1,15 +1,15 @@
module es {
export class ComponentTypeManager{
export class ComponentTypeManager {
private static _componentTypesMask: Map<any, number> = new Map<any, number>();
public static add(type){
public static add(type) {
if (!this._componentTypesMask.has(type))
this._componentTypesMask[type] = this._componentTypesMask.size;
}
public static getIndexFor(type){
public static getIndexFor(type) {
let v = -1;
if (!this._componentTypesMask.has(type)){
if (!this._componentTypesMask.has(type)) {
this.add(type);
v = this._componentTypesMask.get(type);
}

View File

@@ -1,5 +1,5 @@
module es {
export class EntityList{
export class EntityList {
public scene: Scene;
/**
* 添加到场景中的实体列表
@@ -27,23 +27,23 @@ module es {
*/
public _tempEntityList: Entity[] = [];
constructor(scene: Scene){
constructor(scene: Scene) {
this.scene = scene;
}
public get count(){
public get count() {
return this._entities.length;
}
public get buffer(){
public get buffer() {
return this._entities;
}
public markEntityListUnsorted(){
public markEntityListUnsorted() {
this._isEntityListUnsorted = true;
}
public markTagUnsorted(tag: number){
public markTagUnsorted(tag: number) {
this._unsortedTags.push(tag);
}
@@ -51,7 +51,7 @@ module es {
* 将实体添加到列表中。所有生命周期方法将在下一帧中被调用。
* @param entity
*/
public add(entity: Entity){
public add(entity: Entity) {
if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity);
}
@@ -60,14 +60,14 @@ module es {
* 从列表中删除一个实体。所有生命周期方法将在下一帧中被调用。
* @param entity
*/
public remove(entity: Entity){
if (!this._entitiesToRemove.contains(entity)){
public remove(entity: Entity) {
if (!this._entitiesToRemove.contains(entity)) {
console.warn(`You are trying to remove an entity (${entity.name}) that you already removed`);
return;
}
// 防止在同一帧中添加或删除实体
if (this._entitiesToAdded.contains(entity)){
if (this._entitiesToAdded.contains(entity)) {
this._entitiesToAdded.remove(entity);
return;
}
@@ -79,7 +79,7 @@ module es {
/**
* 从实体列表中删除所有实体
*/
public removeAllEntities(){
public removeAllEntities() {
this._unsortedTags.length = 0;
this._entitiesToAdded.length = 0;
this._isEntityListUnsorted = false;
@@ -88,7 +88,7 @@ module es {
// 它们仍然在_entitiesToRemove列表中该列表将由更新列表处理。
this.updateLists();
for (let i = 0; i < this._entities.length; i ++){
for (let i = 0; i < this._entities.length; i++) {
this._entities[i]._isDestroyed = true;
this._entities[i].onRemovedFromScene();
this._entities[i].scene = null;
@@ -106,9 +106,9 @@ module es {
return this._entities.contains(entity) || this._entitiesToAdded.contains(entity);
}
public getTagList(tag: number){
public getTagList(tag: number) {
let list = this._entityDict.get(tag);
if (!list){
if (!list) {
list = [];
this._entityDict.set(tag, list);
}
@@ -116,31 +116,31 @@ module es {
return this._entityDict.get(tag);
}
public addToTagList(entity: Entity){
public addToTagList(entity: Entity) {
let list = this.getTagList(entity.tag);
if (!list.contains(entity)){
if (!list.contains(entity)) {
list.push(entity);
this._unsortedTags.push(entity.tag);
}
}
public removeFromTagList(entity: Entity){
public removeFromTagList(entity: Entity) {
let list = this._entityDict.get(entity.tag);
if (list){
if (list) {
list.remove(entity);
}
}
public update(){
for (let i = 0; i < this._entities.length; i++){
public update() {
for (let i = 0; i < this._entities.length; i++) {
let entity = this._entities[i];
if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0))
entity.update();
}
}
public updateLists(){
if (this._entitiesToRemove.length > 0){
public updateLists() {
if (this._entitiesToRemove.length > 0) {
let temp = this._entitiesToRemove;
this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp;
@@ -157,12 +157,12 @@ module es {
this._tempEntityList.length = 0;
}
if (this._entitiesToAdded.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)){
if (!this._entities.contains(entity)) {
this._entities.push(entity);
entity.scene = this.scene;
@@ -178,12 +178,12 @@ module es {
this._isEntityListUnsorted = true;
}
if (this._isEntityListUnsorted){
if (this._isEntityListUnsorted) {
this._entities.sort();
this._isEntityListUnsorted = false;
}
if (this._unsortedTags.length > 0){
if (this._unsortedTags.length > 0) {
this._unsortedTags.forEach(tag => {
this._entityDict.get(tag).sort();
});
@@ -196,8 +196,8 @@ module es {
* 返回找到的第一个实体的名称。如果没有找到则返回null。
* @param name
*/
public findEntity(name: string){
for (let i = 0; i < this._entities.length; i ++){
public findEntity(name: string) {
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].name == name)
return this._entities[i];
}
@@ -209,11 +209,11 @@ module es {
* 返回带有标记的所有实体的列表。如果没有实体具有标记则返回一个空列表。可以通过ListPool.free将返回的列表放回池中。
* @param tag
*/
public entitiesWithTag(tag: number){
public entitiesWithTag(tag: number) {
let list = this.getTagList(tag);
let returnList = ListPool.obtain<Entity>();
for (let i = 0; i < list.length; i ++)
for (let i = 0; i < list.length; i++)
returnList.push(list[i]);
return returnList;
@@ -223,9 +223,9 @@ module es {
* 返回t类型的所有实体的列表。返回的列表可以通过ListPool.free放回池中。
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[]{
public entitiesOfType<T extends Entity>(type): T[] {
let list = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i] instanceof type)
list.push(this._entities[i] as T);
}
@@ -242,17 +242,17 @@ module es {
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].enabled){
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 ++){
for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i];
if (entity.enabled){
if (entity.enabled) {
let comp = entity.getComponent<T>(type);
if (comp)
return comp;
@@ -266,17 +266,17 @@ module es {
* 返回在类型t的场景中找到的所有组件。返回的列表可以通过ListPool.free放回池中。
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[]{
public findComponentsOfType<T extends Component>(type): T[] {
let comps = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){
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 ++){
for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i];
if (entity.enabled)
entity.getComponents(type,comps);
entity.getComponents(type, comps);
}
return comps;

View File

@@ -2,64 +2,52 @@ module es {
export class EntityProcessorList {
private _processors: EntitySystem[] = [];
public add(processor: EntitySystem){
public add(processor: EntitySystem) {
this._processors.push(processor);
}
public remove(processor: EntitySystem){
public remove(processor: EntitySystem) {
this._processors.remove(processor);
}
public onComponentAdded(entity: Entity){
public onComponentAdded(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onComponentRemoved(entity: Entity){
public onComponentRemoved(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onEntityAdded(entity: Entity){
public onEntityAdded(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onEntityRemoved(entity: Entity){
public onEntityRemoved(entity: Entity) {
this.removeFromProcessors(entity);
}
protected notifyEntityChanged(entity: Entity){
for (let i = 0; i < this._processors.length; i ++){
this._processors[i].onChanged(entity);
}
}
protected removeFromProcessors(entity: Entity){
for (let i = 0; i < this._processors.length; i ++){
this._processors[i].remove(entity);
}
}
public begin(){
public begin() {
}
public update(){
for (let i = 0; i < this._processors.length; i++){
public update() {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].update();
}
}
public lateUpdate(){
for (let i = 0; i < this._processors.length; i ++){
public lateUpdate() {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].lateUpdate();
}
}
public end(){
public end() {
}
public getProcessor<T extends EntitySystem>(): T{
for (let i = 0; i < this._processors.length; i ++){
public getProcessor<T extends EntitySystem>(): T {
for (let i = 0; i < this._processors.length; i++) {
let processor = this._processors[i];
if (processor instanceof EntitySystem)
return processor as T;
@@ -67,5 +55,17 @@ module es {
return null;
}
protected notifyEntityChanged(entity: Entity) {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].onChanged(entity);
}
}
protected removeFromProcessors(entity: Entity) {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].remove(entity);
}
}
}
}

View File

@@ -1,28 +1,28 @@
module es {
export class Matcher{
export class Matcher {
protected allSet = new BitSet();
protected exclusionSet = new BitSet();
protected oneSet = new BitSet();
public static empty(){
public static empty() {
return new Matcher();
}
public getAllSet(){
public getAllSet() {
return this.allSet;
}
public getExclusionSet(){
public getExclusionSet() {
return this.exclusionSet;
}
public getOneSet(){
public getOneSet() {
return this.oneSet;
}
public IsIntersted(e: Entity){
if (!this.allSet.isEmpty()){
for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)){
public IsIntersted(e: Entity) {
if (!this.allSet.isEmpty()) {
for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)) {
if (!e.componentBits.get(i))
return false;
}
@@ -37,7 +37,7 @@ module es {
return true;
}
public all(...types: any[]): Matcher{
public all(...types: any[]): Matcher {
types.forEach(type => {
this.allSet.set(ComponentTypeManager.getIndexFor(type));
});
@@ -45,7 +45,7 @@ module es {
return this;
}
public exclude(...types: any[]){
public exclude(...types: any[]) {
types.forEach(type => {
this.exclusionSet.set(ComponentTypeManager.getIndexFor(type));
});
@@ -53,7 +53,7 @@ module es {
return this;
}
public one(...types: any[]){
public one(...types: any[]) {
types.forEach(type => {
this.oneSet.set(ComponentTypeManager.getIndexFor(type));
});

View File

@@ -1,17 +1,16 @@
class ObjectUtils {
/**
* 对象深度拷贝
* @param p any 源对象
* @param c any 目标对象, 不传则返回新对象, 传则合并属性, 相同名字的属性则会覆盖
*/
/**
* 对象深度拷贝
* @param p any 源对象
* @param c any 目标对象, 不传则返回新对象, 传则合并属性, 相同名字的属性则会覆盖
*/
public static clone<T>(p: any, c: T = null): T {
var c = c || <T>{};
for (let i in p) {
if (typeof p[i] === 'object') {
c[i] = p[i] instanceof Array ? [] : {};
this.clone(p[i], c[i]);
}
else {
} else {
c[i] = p[i];
}
}

View File

@@ -1,9 +1,23 @@
class StringUtils {
/**
* 匹配中文字符
* @param str 需要匹配的字符串
* @return
*/
* 特殊符号字符
*/
private static specialSigns: string[] = [
'&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/**
* 匹配中文字符
* @param str 需要匹配的字符串
* @return
*/
public static matchChineseWord(str: string): string[] {
//中文字符的unicode值[\u4E00-\u9FA5]
let patternA: RegExp = /[\u4E00-\u9FA5]+/gim;
@@ -12,7 +26,7 @@ class StringUtils {
/**
* 去除字符串左端的空白字符
* @param target 目标字符串
* @param target 目标字符串
* @return
*/
public static lTrim(target: string): string {
@@ -25,7 +39,7 @@ class StringUtils {
/**
* 去除字符串右端的空白字符
* @param target 目标字符串
* @param target 目标字符串
* @return
*/
public static rTrim(target: string): string {
@@ -36,7 +50,6 @@ class StringUtils {
return target.slice(0, endIndex + 1);
}
/**
* 返回一个去除2段空白字符的字符串
* @param target
@@ -69,7 +82,7 @@ class StringUtils {
* @return 返回执行替换后的字符串
*/
public static replaceMatch(mainStr: string, targetStr: string,
replaceStr: string, caseMark: boolean = false): string {
replaceStr: string, caseMark: boolean = false): string {
let len: number = mainStr.length;
let tempStr: string = "";
let isMatch: boolean = false;
@@ -84,35 +97,18 @@ class StringUtils {
if (isMatch) {
tempStr += replaceStr;
i = i + tempTarget.length - 1;
}
else {
} else {
tempStr += mainStr.charAt(i);
}
}
return tempStr;
}
/**
* 特殊符号字符串
*/
private static specialSigns: string[] = [
'&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/**
* 用html实体换掉字符窜中的特殊字符
* @param str 需要替换的字符串
* @param reversion 是否翻转替换:将转义符号替换为正常的符号
* @return 换掉特殊字符后的字符串
* @param str 需要替换的字符串
* @param reversion 是否翻转替换:将转义符号替换为正常的符号
* @return 换掉特殊字符后的字符串
*/
public static htmlSpecialChars(str: string, reversion: boolean = false): string {
let len: number = this.specialSigns.length;
@@ -133,27 +129,27 @@ class StringUtils {
/**
* 给数字字符前面添 "0"
*
* <pre>
*
* trace( StringFormat.zfill('1') );
* // 01
*
* trace( StringFormat.zfill('16', 5) );
* // 00016
*
* trace( StringFormat.zfill('-3', 3) );
* // -03
*
* </pre>
*
* @param str 要进行处理的字符串
* @param width 处理后字符串的长度,
* 如果str.length >= width将不做任何处理直接返回原始的str。
* @return
*
*/
* 给数字字符前面添 "0"
*
* <pre>
*
* trace( StringFormat.zfill('1') );
* // 01
*
* trace( StringFormat.zfill('16', 5) );
* // 00016
*
* trace( StringFormat.zfill('-3', 3) );
* // -03
*
* </pre>
*
* @param str 要进行处理的字符串
* @param width 处理后字符串的长度,
* 如果str.length >= width将不做任何处理直接返回原始的str。
* @return
*
*/
public static zfill(str: string, width: number = 2): string {
if (!str) {
return str;
@@ -185,7 +181,7 @@ class StringUtils {
/**
* 翻转字符串
* @param str 字符串
* @param str 字符串
* @return 翻转后的字符串
*/
public static reverse(str: string): string {
@@ -198,14 +194,14 @@ class StringUtils {
/**
* 截断某段字符串
* @param str 目标字符串
* @param start 需要截断的起始索引
* @param len 截断长度
* @param order 顺序true从字符串头部开始计算false从字符串尾巴开始结算。
* @return 截断后的字符串
* @param str 目标字符串
* @param start 需要截断的起始索引
* @param len 截断长度
* @param order 顺序true从字符串头部开始计算false从字符串尾巴开始结算。
* @return 截断后的字符串
*/
public static cutOff(str: string, start: number,
len: number, order: boolean = true): string {
len: number, order: boolean = true): string {
start = Math.floor(start);
len = Math.floor(len);
let length: number = str.length;
@@ -215,8 +211,7 @@ class StringUtils {
let newStr: string;
if (order) {
newStr = str.substring(0, s) + str.substr(e, length);
}
else {
} else {
s = length - 1 - start - len;
e = s + len;
newStr = str.substring(0, s + 1) + str.substr(e + 1, length);

View File

@@ -6,15 +6,15 @@ module es {
public static sharedCanvas: HTMLCanvasElement;
public static sharedContext: CanvasRenderingContext2D;
public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement{
if (!this.sharedCanvas){
public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement {
if (!this.sharedCanvas) {
this.sharedCanvas = egret.sys.createCanvas();
this.sharedContext = this.sharedCanvas.getContext("2d");
}
let w = texture.$getTextureWidth();
let h = texture.$getTextureHeight();
if (!rect){
if (!rect) {
rect = egret.$TempRectangle;
rect.x = 0;
rect.y = 0;
@@ -44,8 +44,7 @@ module es {
}
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
}
else {
} else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据填入canvas
@@ -71,8 +70,7 @@ module es {
}
return surface;
}
else {
} else {
let bitmapData = texture;
let offsetX: number = Math.round(bitmapData.$offsetX);
let offsetY: number = Math.round(bitmapData.$offsetY);
@@ -90,8 +88,7 @@ module es {
let surface = this.convertImageToCanvas(texture, rect);
let result = surface.toDataURL(type, encoderOptions);
return result;
}
catch (e) {
} catch (e) {
egret.$error(1033);
}
return null;
@@ -117,7 +114,7 @@ module es {
success: function (res) {
//todo
}
})
});
return result;
}
@@ -135,8 +132,7 @@ module es {
if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
}
else {
} else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据
@@ -147,8 +143,7 @@ module es {
let surface = this.convertImageToCanvas(texture);
let result = this.sharedContext.getImageData(x, y, width, height).data;
return <number[]><any>result;
}
catch (e) {
} catch (e) {
egret.$error(1039);
}
}

View File

@@ -9,22 +9,21 @@ module es {
public static timeScale = 1;
/** 已传递的帧总数 */
public static frameCount = 0;
private static _lastTime = 0;
/** 自场景加载以来的总时间 */
public static _timeSinceSceneLoad;
private static _lastTime = 0;
public static update(currentTime: number){
public static update(currentTime: number) {
let dt = (currentTime - this._lastTime) / 1000;
this.deltaTime = dt * this.timeScale;
this.unscaledDeltaTime = dt;
this._timeSinceSceneLoad += dt;
this.frameCount ++;
this.frameCount++;
this._lastTime = currentTime;
}
public static sceneChanged(){
public static sceneChanged() {
this._timeSinceSceneLoad = 0;
}
@@ -32,7 +31,7 @@ module es {
* 允许在间隔检查。只应该使用高于delta的间隔值否则它将始终返回true。
* @param interval
*/
public static checkEvery(interval: number){
public static checkEvery(interval: number) {
// 我们减去了delta因为timeSinceSceneLoad已经包含了这个update ticks delta
return (this._timeSinceSceneLoad / interval) > ((this._timeSinceSceneLoad - this.deltaTime) / interval);
}

View File

@@ -1,9 +1,9 @@
class TimeUtils {
/**
* 计算月份ID
* @param d 指定计算日期
* @returns 月ID
*/
* 计算月份ID
* @param d 指定计算日期
* @returns 月ID
*/
public static monthId(d: Date = null): number {
d = d ? d : new Date();
let y = d.getFullYear();
@@ -35,7 +35,8 @@ class TimeUtils {
d = d ? d : new Date();
let c: Date = new Date();
c.setTime(d.getTime());
c.setDate(1); c.setMonth(0);//当年第一天
c.setDate(1);
c.setMonth(0);//当年第一天
let year: number = c.getFullYear();
let firstDay: number = c.getDay();
@@ -51,7 +52,8 @@ class TimeUtils {
}
let num: number = this.diffDay(d, c, false);
if (num < 0) {
c.setDate(1); c.setMonth(0);//当年第一天
c.setDate(1);
c.setMonth(0);//当年第一天
c.setDate(c.getDate() - 1);
return this.weekId(c, false);
}
@@ -66,7 +68,8 @@ class TimeUtils {
}
if (first && (!max || endDay < 4)) {
c.setFullYear(c.getFullYear() + 1);
c.setDate(1); c.setMonth(0);//当年第一天
c.setDate(1);
c.setMonth(0);//当年第一天
return this.weekId(c, false);
}
}
@@ -151,9 +154,9 @@ class TimeUtils {
/**
* 秒数转换为时间形式。
* @param time 秒数
* @param partition 分隔符
* @param showHour 是否显示小时
* @param time 秒数
* @param partition 分隔符
* @param showHour 是否显示小时
* @return 返回一个以分隔符分割的时, 分, 秒
*
* 比如: time = 4351; secondToTime(time)返回字符串01:12:31;