String of moving sprites following the player, most efficient way to do it?


I'm working on a JavaScript game using Phaser, where the player picks up blobs and the blobs then follow the player. So there will be a string of sprites following the player's movements, kind of like the "options" in Gradius or the line of balls in the game Zuma.

from my phaser test program, a moving string of blobs

My question is, what is the best way to get this effect? At the moment my method is like this:

  1. Keep a large array of x/y positions
  2. For each frame update, go to next array index
  3. Put the player x/y position in the array at current index
  4. For each blob, keep a separate array index and copy the x/y position from that index.

It works, but I suspect there will problems with performance on mobile, as even on laptop it sometimes lags. Also when the line of blobs gets longer, the array needs to be resized. Although that could be solved by just making the array maximum size.

Any ideas for most efficient and fastest ideas for this, which datatypes to use, best-practices etc? The fastest performance is most important.

Here's my code so far:

function create() {
    // create the guy
    _grpblobs = game.add.group();
    _thedude = game.add.sprite(0, 0, 'phaserdude');
    _idxoff = 0;

    // add blobs
    for (var i=0; i<40; i++) {
        var blob = game.add.sprite(0, 0, 'orbs', (i%6));
        _grpblobs.add(blob);
    };

    // array to keep track of positions
    for (var i=0; i<1000; i++) {
        _blobpos[i] = 0;
    };

    // mouse input for testing
    window.addEventListener("mousemove", onGameMouseMove);
}

function onGameMouseMove(evt) {
    _thedude.x = evt.x;
    _thedude.y = evt.y;
}

function update() {
    // the main guy current position
    _blobpos[_idxoff]   = _thedude.x;
    _blobpos[_idxoff+1] = _thedude.y;

    // -2 because it's 2 values; x value and y value
    _idxoff = _idxoff - 2;
    if (_idxoff < 0) _idxoff = _idxoff + 1000;

    // update blob positions
    for (var i=0; i < _grpblobs.length; i++) {
        var idx = _idxoff + ( (i+1) * 20);
        idx = idx % 1000;

        _grpblobs.children[i].x = _blobpos[idx];
        _grpblobs.children[i].y = _blobpos[idx+1];
    }
}

Answers: