Game Development Reference
In-Depth Information
base
.Update(gameTime);
if
(!
this
.Visible || velocity == Vector2.Zero)
return
;
As you can see, we first call the
Update
method of the base class. Since the
SpriteGameObject
class does not override the
Update
method, this will call the
Update
method of the
GameObject
class, which will update the position of the object by
adding the velocity multiplied by the elapsed game time. Now, we have to check
if we collide with another game object. Because of the check we do at the start
of the
Update
method, we only do this for animals that are both visible and mov-
ing.
If the animal is moving, we need to know what tile it is currently moving into.
Then we can check what kind of tile it is, and if there are other game objects located
at that tile. For this, we will add a method called
GetCurrentBlock
to the
Animal
class.
How can we calculate the tile we are moving into? When a penguin is moving to the
left, we could calculate the
x
index of the tile as follows:
int
x=(
int
)position.X / tilefield.CellWidth;
Because of the cast to
int
, we will end up at the tile that the left position of the
sprite is in. However, this does not work correctly when we fall off the left end of
the playing field. When we move out of the playing field, we will get an
x
value of
zero, whereas we would like to have an
x
value of
−
1 (the non-existent tile to the
left of the playing field). The reason that this happens is that the cast to
int
truncates
the
float
value. So, if the outcome of
position.X / tilefield.ObjectWidth
equals
0
.
999
f
,
we would end up with zero and not with minus one. Fortunately, the
Math
class has
a method called
Floor
that does exactly what we want. We use this method to create
an object of type
Point
that contains the
x
- and
y
-indices of the tile we are currently
in:
−
Point p =
new
Point((
int
)Math.Floor(position.X / tilefield.CellWidth),
(
int
)Math.Floor(position.Y / tilefield.CellHeight));
However, this only finds the correct tile when we are moving
left or down
. When we
are moving to the right, for example, we want to calculate the tile that the
rightmost
pixel
of the penguin sprite moves into. Therefore, if the
x
velocity is positive, we
add one to the
x
index so that we get the tile to the right-hand side of the animal,
and similar for when the
y
velocity is positive:
if
(velocity.X > 0)
p.X++;
if
(velocity.Y > 0)
p.Y++;
We can now use the
GetCurrentBlock
method to calculate what tile we are currently
moving into, and we can check what kind of tile it is. For that, we will add a few