使更新循环与 Phaser 中的音乐和音符同步

Make update loop in sync with music and notes in Phaser

我试图在音乐在 Phaser 中播放特定时间时出现一些音符,但是当我在控制台中记录 "hit times" 时,它有时只会出现。

我有一个对象 "notes",关键是我希望注释显示的时间:

{
  1377: {
    jam: 1,
    duration: 0.40
  }
}

有 1464 个音符。

但是,在更新循环中,如果我这样做:

update () {
  if (music && music.currentTime) {
    if (notes[music.currentTime]) {
      console.log('notes[music.currentTime].jam', notes[music.currentTime].jam)
    }
  }
}

它只随机记录一些笔记。

你知道为什么吗?

这可能是因为 music.currentTime 在每次更新时递增 ~16 毫秒,因此它可以跳过 notes 对象中的特定时间键。除此之外,我相信时间也可以是一个浮点值,所以它不会完全匹配你在 notes 变量中的键。

另一种实现您想要的方法是将 notes 变量的格式更改为数组,以便以后可以以不同的方式访问它:

var notes = [    
    ...
    {'start': 1377, 'jam': 1, 'duration': 0.40},
    {'start': 2456, 'jam': 1, 'duration': 0.30},
    ...
];

// Index of the first note that will be played.
// Will be incremented by 1 or more with some update() calls,
// depending on the time that passed.
var nextNote = 0;

function update() {
    // Process all notes that are now in the past
    // compared to the current time of the playing music,
    // but skip notes that have been already played before.
    while (music && nextNote < notes.length && notes[nextNote].start <= music.currentTime) {
        console.log(notes[nextNote]);
        nextNote += 1;
    }
}

要使此方法起作用,notes 数组必须按升序保存开始时间。