Game Development Reference
In-Depth Information
Integrating ObjectPool With QuadTree
We have implemented a
QuadTree
, but it is not yet incorporated into our game. To do
that, we will hook it into
ObjectPool
and try to keep the old interface intact, so that
ObjectPool#nearby
will still work as usual, but will be able to cope with way more
objects than before.
10-partitioning/entities/object_pool.rb
1
class
ObjectPool
2
attr_accessor
:map
,
:camera
,
:objects
3
4
def
size
5
@objects
.
size
6
end
7
8
def
initialize
(box)
9
@tree
=
QuadTree
.
new(box)
10
@objects
= []
11
end
12
13
def
add
(object)
14
@objects
<<
object
15
@tree
.
insert(object)
16
end
17
18
def
tree_remove
(object)
19
@tree
.
remove(object)
20
end
21
22
def
tree_insert
(object)
23
@tree
.
insert(object)
24
end
25
26
def
update_all
27
@objects
.
map(
&
:update
)
28
@objects
.
reject!
do
|
o
|
29
if
o
.
removable?
30
@tree
.
remove(o)
31
true
32
end
33
end
34
end
35
36
def
nearby
(object, max_distance)
37
cx, cy
=
object
.
location