Game Development Reference
In-Depth Information
Fig. 5.2
Calculating the
angle of the barrel based on
the mouse position
Texture2D background, cannonBarrel;
Vector2 barrelPosition, barrelOrigin;
We will draw the cannon barrel at an angle using the nine-parameter version of the
Draw
method that we introduced in this chapter. This means that we need to store
the current angle of the barrel in a member variable as well:
float
angle;
We will update the value of this angle in the
Update
method. In the
LoadContent
method, we load the sprites and we assign a value to the
barrelPosition
variable, as
follows:
background = Content.Load<Texture2D>("spr_background");
cannonBarrel = Content.Load<Texture2D>("spr_cannon_barrel");
barrelPosition =
new
Vector2(72, 405);
The position of the barrel is chosen such that it fits nicely on the cannon base
that is already drawn on the background. The barrel image contains a circular part
with the actual barrel attached to it. We want the barrel to rotate around the cen-
ter of the circular part. That means that we have to set this center as the origin.
Since the circle part is on the left part of the sprite, and the radius of this cir-
cle is
cannonBarrel.Height / 2
, we calculate the barrel origin as follows (also in the
LoadContent
method):
barrelOrigin =
new
Vector2(cannonBarrel.Height, cannonBarrel.Height) / 2;
In the
Update
method, we can now update the value of the angle based on the
current mouse position. The first step is to retrieve the current mouse position:
MouseState mouse = Mouse.GetState();
Now we need to calculate at what angle the barrel should be drawn based on the
current mouse position. This situation is depicted in Fig.
5.2
. We can calculate that
angle using the trigonometric
tangent
function, which is given as follows:
opposite
adjacent
.
tan
(angle)
=