group.get()
Gets the sprite at index i of the group.
Every sprite that you add to a group is given an index number based on the order that it was inserted, starting with index number zero. Sprites in a group are usually acted upon identically using the Group functions provided, but some animations or games require different actions for different sprites in a group. Using a loop and group.get(i)
allows you to act upon each sprite individually from a group.
Examples
Go for the Gold
Find up to 3 gold coins hidden randomly. You have 8 guesses.
// Find up to 3 gold coins hidden randomly. You have 8 guesses.
var lose = createGroup();
var win = createGroup();
var winCount=0;
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
if (winCount<3 && randomNumber(1,16)<4) {
winCount=winCount+1;
win.add(createSprite(i*100+50, j*100+50, 50, 50));
}
else {
lose.add(createSprite(i*100+50, j*100+50, 50, 50));
}
}
}
var attempt=0, hit=0;
function draw() {
background("white");
drawSprites();
if (attempt<8 && hit < winCount) {
for (var i = 0; i < winCount; i++) {
if (mouseIsOver(win.get(i)) && mouseWentDown("leftButton")) {
attempt=attempt+1;
hit=hit+1;
win.get(i).setAnimation("coin_gold_1");
}
}
for (var j = 0; j < 16-winCount; j++) {
if (mouseIsOver(lose.get(j)) && mouseWentDown("leftButton")) {
attempt=attempt+1;
lose.get(j).destroy();
}
}
}
else {
textSize(50);
text("HITS = "+hit, 100, 215);
}
}
// Number the sprites.
var group = createGroup();
for (var i = 0; i < 20; i++) {
group.add(createSprite(randomNumber(0, 400), randomNumber(0, 400),randomNumber(10, 20),randomNumber(10, 20)));
}
fill("red");
function draw() {
background("white");
drawSprites();
for (var i = 0; i < 20; i++) {
var temp=group.get(i);
text(i, temp.x, temp.y);
}
}
Syntax
group.get(i)
Parameters
Name | Type | Required? | Description |
---|---|---|---|
i | Number | The index position of a sprite from the group. |
Returns
Tips
- Groups of sprites all have the same functions and you use the dot notation (combining the name of the group, followed by a dot, with the function name) to call the function for that group of sprites.
- Any changes to the properties of a sprite will not be seen until after
drawSprites()
is called.
Found a bug in the documentation? Let us know at support@code.org.