Game Development Reference
In-Depth Information
and the enemy bullets will only hurt the player. To let the player know which
bullets are which, they are given different colors.
You may see the position getter and setter and color setter and wonder if it would
be better just to make the sprite class public. Then if we wanted to change the
position or color, we could just alter the bullet sprite directly. Every situation
is different but as a general rule, it's better to keep more data private and provide
an interface to the data that needs to be changed. Also bullet.SetColor() is
more straightforward to read than bullet.Sprite.SetColor() .
The constructor takes in a texture for the bullet and sets some default values for
the color, direction, and speed. The speed is measured in pixels per second. The
final two methods are Render and Update . The Update loop updates
the position of the bullet using the direction and speed. The position increase
is scaled by the amount of time since the last frame, so the movement will
be consistent on any speed of computer. The render is quite straightforward; it
just draws the bullet sprite. Both the render and update loops do nothing if the
bullet has its dead flag set to true.
A lot of bullets are going to be flying about and there needs to be a certain
amount of logic to deal with that. Bullets that leave the screen need to be turned
off. A BulletManager class is a fine place to put all this logic. There are two
ways to write a BulletManager class: the simple straightforward way and the
memory-efficient way. The BulletManager introduced here is the straight-
forward type; when an enemy is destroyed on screen its reference is removed
from the BulletManager and the object is destroyed in code; freeing any
memory it was using. Every time the player fires, a new bullet is created. This is
basic, but creating and deleting lots of objects in the game loop is a bad thing; it
will make your code slow if you do it too much. Creation and deletion of objects
tends to slow operations.
A more memory-efficient method of managing the bullets is to have a big list of,
say, 1,000 bullets. Most of the bullets are dead; every time the user fires the list is
searched and a dead bullet is brought to life. No new objects need to be created. If
all 1,000 bullets are alive, then either the player can't fire or a heuristic (such as
bullet that's been alive longest) is used to kill one of the current bullets and let the
player use that one. Recycling bullets in this way is a better way to write
the BulletManager . Once you've seen the simple manager in action, you can
always have a go at converting it to the more memory-efficient one yourself.
 
Search WWH ::




Custom Search