Many Sprites
- What if we want a game with many sprites?
Use a loop
for 0 ≤ i < 100 do var sprite := board→create rectangle(5 0, 50) sprite→set x(math→random(board→width)) sprite→set y(math→random(board→height)) sprite→set speed y(100) end for
- That creates many sprites, but we also need them to do something in response to events
- So in
on every frame
add code to do something when the sprites reach the bottom of the screen - But we can’t the variable sprite does not exist outside of the loop
- It’s only a single sprite anyway, each iteration overwites the variable named sprited created the previous iteration
We need a way to remember or reference many sprites
var sprites := board→create sprite set for 0 ≤ i < 100 do var sprite := board→create rectangle(5 0, 50) sprite→set x(math→random(board→width)) sprite→set y(math→random(board→height)) sprite→set speed y(100) sprites→add(sprite) end for board→on every frame do for each sprite2 in sprites do if sprite2→y > board→height then sprite2→set y(0) else do nothing end if end for each end
- A sprite set is a collection of sprites
- Create a sprite set using the
board→create sprite set
function - Add sprites to it using the
sprites→add
function Do something to the sprites in the sprite set using a
for each
loop
Quiz
- m.socrative.com
- Room name ‘INQ241’