Game Development Reference
In-Depth Information
Since
explosion
sounds
are
triggered
only
once,
when
it
starts
to
explode,
ExplosionSounds
is a static class with
play
method.
Refactoring Bullet
Now, let's go up a little and reimplement our
Bullet
:
05-refactor/entities/bullet.rb
1
class
Bullet
<
GameObject
2
attr_accessor
:x
,
:y
,
:target_x
,
:target_y
,
:speed
,
:fired_at
3
4
def
initialize
(object_pool, source_x, source_y, target_x, target_y)
5
super
(object_pool)
6
@x
,
@y
=
source_x, source_y
7
@target_x
,
@target_y
=
target_x, target_y
8
BulletPhysics
.
new(
self
)
9
BulletGraphics
.
new(
self
)
10
BulletSounds
.
play
11
end
12
13
def
explode
14
Explosion
.
new(object_pool,
@x
,
@y
)
15
mark_for_removal
16
end
17
18
def
fire
(speed)
19
@speed
=
speed
20
@fired_at
=
Gosu
.
milliseconds
21
end
22
end
All physics, graphics and sounds are extracted into individual components, and instead
of managing
Explosion
, it just registers a new
Explosion
with
ObjectPool
and
marks itself for removal in
explode
method.
05-refactor/entities/components/bullet_physics.rb
1
class
BulletPhysics
<
Component
2
START_DIST
= 20
MAX_DIST
= 300
3
4
5
def
initialize
(game_object)
6
super
7
object
.
x, object
.
y
=
point_at_distance(
START_DIST
)