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

孤人 提交于 2019-12-24 02:11:49

问题


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.

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];
    }
}

来源:https://stackoverflow.com/questions/44196855/string-of-moving-sprites-following-the-player-most-efficient-way-to-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!