What is a Group?
In p5play a Group is a collection of and blueprint for sprites with similar traits and behaviors. For example the dots in Pac-Man!
group.length property can be used to
check how many sprites are in a group. In this example the while loop condition is true as long as the dots
group has less than 24 sprites.
In the mini example,
new dots.Sprite creates a sprite
that inherits the dots group's color, y position, and diameter. Each dot is assigned a unique x position.
I call this "soft inheritance" because a group acts as a blueprint for new group sprites.
Setting a group's property to a different value will affect all the sprites in the group! I call this "dynamic inheritance".
Using movement functions like
will cause all the sprites in a group to move.
Arrow function property setters
In p5play, when you set a sprite property in a group to an arrow function, each new sprite created using that group will use the function to evaluate the property.
group.amount gets adjusted, the group will
automatically create or remove sprites to match the set amount.
In this mini example, each gem sprite is assigned a random x and y position.
The overlap function isn't just for handling if two sprites overlap. You can also check if a sprite overlaps with a sprite in a group.
In this mini example the collect function receives as inputs the player and the gem in the gems group that the player sprite is overlapping. That gem gets removed.
You can use the overlap and collide functions on groups as well.
p5play creates an
allSprites group that contains all the sprites in a sketch.
Indexed arrow function setters
When evaluating a group sprite's property you can even use its index!
i is the index of the sprite in the group, which is given as an input parameter to group
they are evaluated.
In this mini example there are two sub groups of the
New sprites created using the
bigBoxes group will
inherit traits from the
boxes group but
not from the
boxes group contains all the sprites in the
group.removeAll function can be used to remove all the sprites from a group.