Search code examples
randompositionspritedrawp5.js

How do I have it so that sprites in a group all spawn in random locations only once in the draw function?


I want to have it in my code such that all of the sprites in a group variable spawn in different locations once in the draw function. The problem I am currently having is that since the draw function constantly repeats, all of the sprites are constantly changing positions due to this; and as you can imagine, they are rapidly moving all across the screen.

  drawSprites(toppingsGroup);
  for (var i = 0; i < toppingsGroup.length; i++) {
     toppingsGroup[i].position.x = 600;
     toppingsGroup[i].position.y = random(height);

}

Solution

  • You have two options:

    1. Move the random position code to the setup() function
    2. Wrap the random position code in an if block such that it only runs once

    Option #1 is trivial, but here is an example of option #2

    let groupPositioned = false;
    
    function draw() {
      if (!groupPositioned) {
        for (var i = 0; i < toppingsGroup.length; i++) {
         toppingsGroup[i].position.x = 600;
         toppingsGroup[i].position.y = random(height);
        }
        groupPositioned = true;
      }
    
      drawSprites(toppingsGroup); 
    }