When you place sprites with a group, you have the ability to both keep track of all sprites of the same type as well as change parameters on all of the sprites at once.
[https://editor.p5js.org/des8963/sketches/H3hykrCfZ](https://prod-files-secure.s3.us-west-2.amazonaws.com/2e0ddbc5-46f0-43d3-abca-17258b8b49b2/32dd553c-ec4d-4ac3-8e6b-665ec1a2a2e8/p5PlayGroup.mp4)
https://editor.p5js.org/des8963/sketches/H3hykrCfZ
In the following code, we create a group called myGroup, set the group parameter’s color and then create 4 sprites. Note all sprites will have the same color and text which have been inherited from the group.
let myGroup;
function setup() {
createCanvas(400, 400);
// create a group
myGroup = new Group();
myGroup.color="#a57548";
myGroup.text="Sprite";
// add 4 sprites to the group
new myGroup.Sprite(100, 100, 30, 'septagon');
new myGroup.Sprite(200, 100, 30, 'septagon');
new myGroup.Sprite(100, 200, 30, 'septagon');
new myGroup.Sprite(200, 200, 30, 'septagon');
}
function draw() {
clear();
}
The group is essentially an array of sprites. We can loop through the sprites, for example the following script will check to see if each of the bubbles leave the canvas (x>width or y>height) and if they leave, the x or y is reset to zero to make the bubbles cycle around.
let myGroup;
function setup() {
createCanvas(400, 400);
myGroup = new Group();
myGroup.d=15;
// create 8 randomly placed sprites
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
}
function draw() {
clear();
// loop through all of the sprites
for (let i=0; i<myGroup.length; i++) {
let aSprite=myGroup[i];
aSprite.x++;
if (aSprite.x>width) {
aSprite.x=0;
}
aSprite.y++;
if (aSprite.y>height) {
aSprite.y=0;
}
}
}
let myGroup;
function setup() {
createCanvas(400, 400);
myGroup = new Group();
myGroup.d=15;
// create 8 randomly placed sprites
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
new myGroup.Sprite(random(5,width-5),random(5,height-5));
}
function moveSprite(aSprite) {
aSprite.x++;
if (aSprite.x>width) {
aSprite.x=0;
}
aSprite.y++;
if (aSprite.y>height) {
aSprite.y=0;
}
}
function draw() {
clear();
// loop through all of the sprites
myGroup.forEach(moveSprite);
}