Authored by LitDev
I recently wrote a TechNet Wiki article describing how to manage arrays of sprites in a game.
For the full article see http://social.technet.microsoft.com/wiki/contents/articles/24857.small-basic-sprite-arrays.aspx .
The following is an excerpt from one section...
Recycling sprites
We often want sprites to appear and disappear. One way to do this is to recycle the sprites from a 'pool', activating and using them as required. This can be good for example to fire bullets or missiles, when we only ever need a limited number on screen at the same time.
The example below fires missiles when the mouse is clicked. A new spriteData property "Status" is used to flag that missiles are active or not. Inactive missiles are hidden and they are shown while they are active on the screen.
Missile Sprite
gw
=
600
gh
=
600
GraphicsWindow
.
Width
=
gw
GraphicsWindow
.
Height
=
gh
GraphicsWindow
.
MouseDown
=
OnMouseDown
CreateSprites
(
)
'Game Loop
While
(
"True"
)
start
=
Clock
.
ElapsedMilliseconds
If
(
mouseDown
)
Then
FireMissile
(
)
mouseDown
=
"False"
EndIf
UpdateSprites
(
)
delay
=
20
-
(
Clock
.
ElapsedMilliseconds
-
start
)
If
(
delay
>
0
)
Then
Program
.
Delay
(
delay
)
EndIf
EndWhile
Sub
CreateSprites
'Sprite dimensions we use the half width and height
spriteWidth
=
ImageList
.
GetWidthOfImage
(
spriteImage
)
/
2
spriteHeight
=
ImageList
.
GetHeightOfImage
(
spriteImage
)
/
2
numSprite
=
50
For
i
=
1
To
numSprite
spriteData
[
"image"
]
=
Shapes
.
AddImage
(
spriteImage
)
spriteData
[
"Xpos"
]
=
spriteWidth
+
Math
.
GetRandomNumber
(
gw
-
2
*
spriteWidth
)
spriteData
[
"Ypos"
]
=
gh
-
spriteHeight
spriteData
[
"Xvel"
]
=
0
spriteData
[
"Yvel"
]
=
-
5
spriteData
[
"Status"
]
=
0
Shapes
.
HideShape
(
spriteData
[
"image"
]
)
sprites
[
i
]
=
spriteData
EndFor
EndSub
Sub
UpdateSprites
For
i
=
1
To
numSprite
spriteData
=
sprites
[
i
]
'get current sprite array
If
(
spriteData
[
"Status"
]
=
1
)
Then
'Reposition sprite center
spriteData
[
"Xpos"
]
=
spriteData
[
"Xpos"
]
+
spriteData
[
"Xvel"
]
spriteData
[
"Ypos"
]
=
spriteData
[
"Ypos"
]
+
spriteData
[
"Yvel"
]
'Move sprite center
Shapes
.
Move
(
spriteData
[
"image"
]
,
spriteData
[
"Xpos"
]
-
spriteWidth
,
spriteData
[
"Ypos"
]
-
spriteHeight
)
'Sprite finished with
If
(
spriteData
[
"Ypos"
]
<
-
spriteHeight
)
Then
spriteData
[
"Status"
]
=
0
Shapes
.
HideShape
(
spriteData
[
"image"
]
)
EndIf
sprites
[
i
]
=
spriteData
'save updated sprite array (it may have been modified)
EndIf
EndFor
EndSub
Sub
FireMissile
For
i
=
1
To
numSprite
spriteData
=
sprites
[
i
]
'get current sprite array
If
(
spriteData
[
"Status"
]
=
0
)
Then
spriteData
[
"Status"
]
=
1
Shapes
.
ShowShape
(
spriteData
[
"image"
]
)
spriteData
[
"Xpos"
]
=
GraphicsWindow
.
MouseX
spriteData
[
"Ypos"
]
=
gh
-
spriteHeight
sprites
[
i
]
=
spriteData
'save updated sprite array (it may have been modified)
i
=
numSprite
'End loop
EndIf
EndFor
EndSub
Sub
OnMouseDown
mouseDown
=
"True"
EndSub