cocos creator从零开发简单框架(24)-定时管理器

UIPanel对应的脚本是普通的类而不是Cocos Creator的组件,所以不能使用组件的schedulescheduleOnce这些定时接口,这样框架就需要提供一个自己的定时管理器。

新建framework/scripts/base/Singleton.ts,这是单例基类,内容如下 。

export default class Singleton {
    private static _instance: any = null

    protected static getInstance<T>(): T {
        if (this._instance === null) {
            this._instance = new this()
        }

        return this._instance
    }

    protected constructor() { }
}

新建framework/scripts/manager/TimerMgr.ts,主要是监听cc.Director.EVENT_BEFORE_UPDATE事件,再调用cc.director.getDeltaTime()获取上一帧到这一帧的时间,内容如下 。

import Singleton from "../base/Singleton"


interface ITimer {
    tick: number

    interval: number
    cb: Function
    ctx: any
    repeat: number
    key: string
}


export default class TimerMgr extends Singleton {
    public static get inst() {
        return super.getInstance<TimerMgr>()
    }


    private _timers: ITimer[] = []


    constructor() {
        super()

        cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, this.update, this)
    }


    /**
    添加定时器
    @param interval 定时间隔, 单位毫秒(0 每帧调用)
    @param cb 定时回调函数
    @param ctx 回调函数对象, 可以为空
    @param repeat 重复次数, 默认为 1 次(小于等于 0 一直调用)
    @param key 当循环遍历对象做定时用同一个回调函数时可以添加 key 做区别
    
    @example 
    `js
    // 3秒 后回调 echo, 共 1 次
    TimerMgr.inst.add(3000, this.echo)
    // 每 0.5秒 回调 echo, 共 5 次
    TimerMgr.inst.add(500, this.echo, this, 5)
    // 每秒回调 echo, 无限次
    TimerMgr.inst.add(500, this.echo, this, 0)
    `
    */
    public add(interval: number, cb: Function, ctx?: any, repeat: number = 1, key?: string) {
        if (cb == null) {
            cc.error('TimerMgr.add 参数错误')
            return
        }

        if (this.exist(cb, ctx, key)) {
            cc.error('TimerMgr.add 定时器已存在')
            return
        }

        this._timers.push({ tick: 0, interval, cb, ctx, repeat, key })
    }

    public del(cb: Function, ctx?: any, key?: string) {
        const index = this._timers.findIndex(timer => cb === timer.cb && timer.ctx === ctx && timer.key === key)
        index >= 0 && this._timers.splice(index, 1)
    }

    public clear(ctx: any) {
        if (!ctx) return

        for (let i = this._timers.length - 1; i >= 0; i--) {
            const timer = this._timers[i]
            if (timer.ctx == ctx) {
                this._timers.splice(i, 1)
            }
        }
    }


    private update() {
        const dt = cc.director.getDeltaTime()

        for (let i = this._timers.length - 1; i >= 0; i--) {
            const timer = this._timers[i]

            timer.tick += dt * 1000
            if (timer.tick < timer.interval) {
                continue
            }

            timer.tick -= timer.interval

            if (timer.repeat <= 0) {
                if (timer.interval == 0) {
                    timer.cb.call(timer.ctx, dt)
                } else {
                    timer.cb.call(timer.ctx, timer.key)
                }
                continue
            }

            timer.repeat--
            if (timer.repeat == 0) {
                this._timers.splice(i, 1)
            }

            timer.cb.call(timer.ctx, timer.key)
        }
    }


    private exist(cb: Function, ctx?: any, key?: string): boolean {
        const index = this._timers.findIndex(timer => cb === timer.cb && timer.ctx === ctx && timer.key === key)
        return index >= 0
    }
}
### Cocos Creator 框架介绍 Cocos Creator 是一款专为游戏开发者设计的强大编辑器和框架,支持2D和简单的3D游戏开发。其核心优势在于提供了直观的可视化界面以及高效的脚本编写环境。 #### 基础架构与特性 - **网络通信**:内置了Socket和HTTP两种方式来处理客户端和服务端之间的交互[^1]。 - **资源管理**:提供了一套完整的解决方案用于加载、卸载各种类型的资产文件,并能有效管理和优化这些资源以提高性能。 - **UI管理系统**:不仅能够轻松创建复杂的用户界面布局,还特别针对可滚动列表视图(Recycle ListView)、滚屏视图(Recycle ScrollView)进行了专门的支持。 - **热更新机制**:允许应用程序在不重新安装的情况下获取最新的功能改进或修复漏洞。 - **定时调度与事件驱动模型**:通过集成强大的计时器服务和灵活的消息传递体系结构,使得复杂逻辑变得简单易懂。 - **动画效果制作**:Tween工具可以用来构建平滑过渡的效果;同时对于音效也有很好的兼容性和控制力。 另外,在某些特定版本中采用了PureMVC模式进行分层设计,从而实现了更好的模块化分离[^2]。例如: - 多分辨率自适应调整; - 数据持久化的实现; - 导航系统的搭建等高级特性的加入让整个平台更加完善。 最后值得注意的是,为了方便不同层次的需求调用,部分重要对象被封装成单例形式存在,比如消息中心继承自`MessageCenter`类以便全局范围内发送接收通知信息[^3]。 ```javascript // 创建一个新的场景并启动它 cc.director.loadScene('game'); // 使用 tween 工具创建一个淡入动画 let node = this.node; cc.tween(node).to(0.5, { opacity: 255 }).start(); // 发送一条广播给所有监听者 this.messageCenter.emit('event_name', data); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值