5

I've been working on a library in JavaScript using p5.js for sprite rendering. I've got an object for storing sprite information which is then added to an array that has a function that updates every frame.

function createsprite(img, x, y, width, height, layer, tag){
    var sprite = {
        img: img,
        xpos: x,
        ypos: y,
        width: width,
        height: height,
        id: spriteid,
        clayer: layer,
        stag: tag,
        removesprite: removeobject(this.id),
        frozen: false
    };
    spriteid++;
    spritesarray.push(sprite)
    return sprite;
    
}

Then I am using this function to draw the sprites, which are added to the array in the function above.

function drawsprites(){  
    for(let i = 0; i < spritesarray.length; i++){
        image(spritesarray[i].img, spritesarray[i].xpos, spritesarray[i].ypos)
    }
}

My issue is that I am trying to modify the xpos of the object but it is only stored temporarily, then it resets to default. I am not sure why this occurs: I am attempting to modify the property of the object but, when the array is drawn with the drawsprites() function, any modification I made to sprite1 is reset to default.

function draw() {
    
    background(220);
    sprite1 = createsprite(img, 0,0,0,0, 1, "Player")
    if(keyIsDown(DOWN_ARROW)){
      
      sprite1.ypos -= 10;

    }
    startnumber++;
    
    drawsprites();
    
  }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Could you show where you update the xpos and also explain a bit more about how it changes temporarily - did you see the change in a console log or with an alert or on the screen position...? Also, though this is probably not relevant to your current problem, where does the spriteid come from that is used while creating the sprite? – A Haworth Sep 24 '20 at 15:17

1 Answers1

2

The issue may be that you create sprite1 over and over again in draw() which means every single frame you make a new sprite, maybe move it 10 pixels, but next frame there's a new sprite at 0,0 again.

In short the issue is not that the ypos updated value doesn't persist, it's that the sprite object altogether doesn't persist because it keeps being replaced (re-assigned to a brand new one, many times a second).

try:

  1. adding let sprite1 at the top of your code
  2. moving sprite1 = createsprite(img, 0,0,0,0, 1, "Player") out of draw() and into setup() (where it gets called once)
  3. test pressing the down arrow: the same sprite1 object in memory should persist

see p5.js reference for variable scope

George Profenza
  • 50,687
  • 19
  • 144
  • 218