0

I have a list where I add/remove elements:

let list = [];
list.push(1);
list.push(2);
list.shift();

Or this could be a map as well:

let res = {};
res['key'] = 3;
res['key2'] = 5;
delete res['key'];

Now I want to render this list/map. I use Pixi.js where there is a scene graph for objects.

So I have some functions to setup and render this scene:

let dS = new Sprite();
addToScene();

function addToScene() {
    // add a sprite to the scene
  scene.addChild(dS);
}

// called once on setup
function init() {
  dS.texture = textures['smile'];
}


// called everytime on render
function render() {
    dS.position.set(x, y);
}

As you can see there is the step of creating sprites, adding the sprites to the scene, initializing with textures, and setting their position on each render time. Now this would be easy if I knew the sprites were static. But as I mentioned above I have a list where I add/remove elements. How do I initialize these sprites associated with each list item, and render them, and add/remove them as they are added/removed from the list.

1

1 Answer 1

0

As far as I know, you cannot "connect" two arrays in the way you want to do it

Meanwhile, the only thing you can do is to create an array with your sprites:

let sprites = [];

Then create your add & remove methods:

function addSprite(id){
    sprites[id] = new Sprite();
    scene.addChild(sprites[id]);
}

function removeSprite(id){
    scene.removeChild(sprites[id]);
    sprites.splice(id,1)
}
2
  • Slight error, delete sprites[id] should be sprites.splice(id,1) as sprites is an array and delete will just make that element undefined or empty. Delete would be appropriate if sprites was an object.
    – PAEz
    Apr 29, 2020 at 2:51
  • Indeed, just corrected it! Jan 27, 2022 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.