Skip to content
hebo edited this page Aug 20, 2020 · 13 revisions

Ticker

framerate

帧频,framerate == 1000/interval

createjs.Ticker.framerate = 10

interval

指示每次ticks的间隔时间(毫秒)。默认值为50(20 fps)。请注意,根据CPU负载的不同,ticks之间的实际时间可能会超过指定的时间。如果使用RAF计时模式,则忽略此属性。

maxDelta

定Tick事件对象中Delta属性的最大值。这在构建基于时间的动画和系统时很有用,以防止由后台选项卡、系统睡眠、警报对话框或其他阻塞例程造成的大时间间隔引起的问题。预期帧持续时间的两倍通常是一个有效值(例如,当以40fps运行时,maxdelta=50)。

paused

When the ticker is paused, all listeners will still receive a tick event, but the paused property of the event will be true. Also, while paused the runTime will not increase. See tick, getTime, and getEventTime for more info.

createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.paused = true;
function handleTick(event) {
  console.log(event.paused)
  console.log(createjs.Ticker.getTime(false)) // 增长
  console.log(createjs.Ticker.getTime(true)) // 不增长
}

timingMode

createjs.Ticker.framerate = 10
// createjs.Ticker.timingMode = createjs.Ticker.TIMEOUT; // 默认是这种模式

// 如果timingMode = createjs.Ticker.RAF,则忽略上面的framerate; fps = 60;
createjs.Ticker.timingMode = createjs.Ticker.RAF

// 如果要用上面的framerate生效必须用RAF_SYNCHED, 最好createjs.Ticker.framerate设为10, 12, 15, 20, 30中的一个值,不然会有性能问题
createjs.Ticker.timingMode = createjs.Ticker.RAF_SYNCHED

getTime( [runTime=false] ) Number static

返回自Ticker通过Ticker/Init初始化以来经过的毫秒数。如果ticker尚未初始化,则返回-1。例如,您可以在时间同步动画中使用它来确定所经过的确切时间量。

参数如果为true,则只会返回未暂停Ticker时经过的时间。If false, the value returned will be total time elapsed since the first tick event listener was added.

getMeasuredFPS ( [ticks] ) Number static

Returns the actual frames / ticks per second.

The actual frames / ticks per second. Depending on performance, this may differ from the target frames per second.

  _update (e) {
    if (this._started && this.state.update) {
      this.state.update(e)
    }

    if (this.config.showfps) {
      this.showfps.innerHTML = Math.round(createjs.Ticker.getMeasuredFPS()) + ' fps'
    }
  }

实现一个简单的Ticker

    // 默认值是先加速后减速的运动函数
    const ease = (x) => {
        return Math.sqrt(1 - Math.pow(x - 1, 2))
    }
    const noop = () => { }

    class Animation {
        constructor(option = {}) {
            this.tickId = 0
            this.value = 0
            this.change = option.change || noop
            this.animationEnd = option.animationEnd || noop
        }

        stop () {
            cancelAnimationFrame(this.tickID)
        }

        to (v, time, user_ease, callback) {
          this._to(v, this._getValue(time, 600), user_ease || ease, this.change, (value) => {
              this.animationEnd.call(this, value)
              callback && callback.call(this, value)
          })
        }

        _to(value, duration, ease, onChange, onEnd) {
            let current = this.value

            let diffValue = value - current

            let startTime = +new Date()
            const toTick = () => {
                let diffTime = +new Date() - startTime
                if (diffTime >= duration) {
                    //el[property] = value;
                    onChange && onChange.call(this, value)
                    onEnd && onEnd.call(this, value)
                    return
                }
                let ratio = ease(diffTime / duration)
                let v = current + diffValue * ratio

                this.tickID = requestAnimationFrame(toTick)
                onChange && onChange.call(this, v)

            }
            toTick()
        }

        _getValue (obj, defaultValue) {
            return obj === void 0 ? defaultValue : obj
        }
    }

    let dom = document.getElementById('test')

    let an = new Animation({
        change(value) {
            dom.style.left = value + 'px'
        },
        animationEnd() {
            console.info('end')
        }
    })

    an.to(1000, 3000, createjs.Ease.sineOut)

delta (通常用dt表示)

the delta time in seconds it took to complete the last frame 本次与上一次tick间隔时间。因为每次tick的间隔时间有微小的差距,所以是一个不断变化的值。

游戏中,常用delta非常有用。常用来算每个tick之间sprite的移动距离。

每次tick的增量移动距离 = 速度 * delta(时间)

updateEnemys(e) {
    let velY
    this.enemyManager.each((enemy, index) => {
      // velX = (magpie.speed * e.delta) / 1000
      // 增量距离(每次tick) = 速度 * 间隔时间
      velY = (enemy.speed * e.delta) / 1500
      if (enemy.nextX >= this.game.width - enemy.width || enemy.nextX < 0) {
        // magpie.direction *= -1
      }
      // magpie.nextX = magpie.x + velX * magpie.direction
      enemy.nextY = enemy.y + velY
      if (enemy.nextY >= this.game.height + 300) {
        this.enemyManager.pooler.put(enemy)
        this.enemyManager.removeAt(index)
      }
    })
  },
   // 来自cocos入门摘星星游戏片断
     properties: {
        // 主角跳跃高度
        jumpHeight: 0,
        // 主角跳跃持续时间
        jumpDuration: 0,
        // 最大移动速度
        maxMoveSpeed: 0,
        // 加速度
        accel: 0,
    },

// 加速度示例
// Player.js
    update: function (dt) {
        // 根据当前加速度方向每帧更新速度
        // 末速度Vt = Vo + at;
        if (this.accLeft) {
            this.xSpeed -= this.accel * dt;
        } else if (this.accRight) {
            this.xSpeed += this.accel * dt;
        }
        // 限制主角的速度不能超过最大值
        if ( Math.abs(this.xSpeed) > this.maxMoveSpeed ) {
            // if speed reach limit, use max speed with current direction
            this.xSpeed = this.maxMoveSpeed * this.xSpeed / Math.abs(this.xSpeed);
        }

        // 根据当前速度更新主角的位置
        this.node.x += this.xSpeed * dt;
    }

Clone this wiki locally