Game Development Reference
In-Depth Information
Here, we calculate the new position of the ball based on the velocity and the time
that has passed since the last update. We access the time that was passed through
the
ElapsedGameTime
property, which gives us the time that was elapsed since the
last update. This property is found in the
GameTime
type, and it gives us an object of
type
TimeSpan
.The
TimeSpan
type has a property called
TotalSeconds
which gives us
a
double
representing the total time span in seconds. Because the velocity is of type
Vector2
, and
Vector2
contains
float
members, we need to cast this
double
valuetoa
float
value. Then, we multiply the velocity by this amount, and we add the outcome
to the current position. Now, if for some reason the last update took a bit longer than
expected, the ball will still have the correct position. Taking the elapsed time into
account is really important. Some older games did not do this and simply updated
the position of an object with a constant velocity factor. As a result, when computers
became faster, these games became more and more difficult to play! Players do not
like this. Therefore: always take the elapsed time into account when calculating
things like velocities or positions.
If the ball is not currently shooting, we are allowed to change the color of the
ball. In this case, we do that by simply copying the color of the cannon to the color
of the ball. That way, we are sure that the color of the ball always matches the
color of the cannon. We can access the color value through the
Cannon
property of
the
GameWorld
object. We have access to the
GameWorld
object through the static
GameWorld
property that we added to the
Painter
class. Here, you can see that the
game world serves as a basic means for objects to interact with each other. In the
case of the ball, the color of the cannon needs to be retrieved so that the ball has the
same color. Furthermore, we also update the position of the ball, as follows:
−
Center;
position = Painter.GameWorld.Cannon.BallPosition
Why do we change the position? When the ball is not shooting, the player can mod-
ify the shooting position of the ball by rotating the barrel of the cannon. Therefore,
we need to calculate the correct ball position here, to ensure that it matches the cur-
rent orientation of the cannon barrel. Also, since the ball is drawn behind the cannon
we need to update its position so that it stays behind the cannon after its barrel is
rotated. In order to do this, we add a new property called
BallPosition
to the
Cannon
class, in which we calculate the position of the ball based on the barrel orientation.
Using the sine and cosine functions, we calculate the new position as follows:
public
Vector2 BallPosition
{
get
{
float
opposite = (
float
)Math.Sin(angle)
∗
cannonBarrel.Width
∗
0.5f;
∗
∗
float
adjacent = (
float
)Math.Cos(angle)
cannonBarrel.Width
0.5f;
return
position +
new
Vector2(adjacent, opposite);
}
}