HTML and CSS Reference
In-Depth Information
Let's take a look at the
createObjectPools()
function now:
function
function
createObjectPools
(){
for
for
(
var
var
ctr
=
0
;
ctr
<
maxParticles
;
ctr
++
){
var
var
newParticle
=
{};
particlePool
.
push
(
newParticle
)
}
console
.
log
(
"particlePool="
+
particlePool
.
length
)
}
As you can see, we simply iterate from
0
to
1
less than the
maxParticles
value and place a
generic object instance at each element in the pool. When a particle is needed, the
createEx-
plode()
function sees whether
particlePool.length
is greater than
0
. If a particle is avail-
able, it is added to the
particles
array after its attributes are set. If no particle is available,
none is used.
NOTE
This functionality can be extended to add a particle as needed to the pool when none is available. We
have not added that functionality to our example, but it is common in some pooling algorithms.
Here is the newly modified
createExplode()
function in its entirety:
function
function
createExplode
(
x
,
y
,
num
,
type
) {
playSound
(
SOUND_EXPLODE
,.
5
);
for
for
(
var
var
partCtr
=
0
;
partCtr
<
num
;
partCtr
++
){
iif
(
particlePool
.
length
>
0
){
newParticle
=
particlePool
.
pop
();
newParticle
.
dx
=
Math
.
random
()
*
3
;
iif
(
Math
.
random
()
<
.
5
){
newParticle
.
dx
* =
−
1
;
}
newParticle
.
dy
=
Math
.
random
()
*
3
;
iif
(
Math
.
random
()
<
.
5
){
newParticle
.
dy
* =
−
1
;
}
newParticle
.
life
=
Math
.
floor
(
Math
.
random
()
*
30
+
30
);
newParticle
.
lifeCtr
=
0
;
newParticle
.
x
=
x
;
newParticle
.
width
=
2
;
newParticle
.
height
=
2
;