Game Development Reference
In-Depth Information
In other words, the angle is then given by
arctan opposite
adjacent
.
=
angle
Calculating the length of the opposite and adjacent sides can be done by calculating
the difference between the current mouse position and the position of the cannon
barrel, as follows:
double opposite = mouse.Y
barrelPosition.Y;
barrelPosition.X;
double adjacent = mouse.X
Now we have to calculate the arc tangent using these values. How do we do this?
Fortunately, the Math class can help us with that. In order to use this class, we need to
place an extra using instruction at the top of our file since the Math class is contained
in the System library:
using System;
The Math class contains many (static!) methods for basic mathematical calculations
among which trigonometric functions like Sin , Cos , Ta n and their inverses Asin , Acos ,
and Atan . However, there is a problem with calling Atan in a situation where the
mouse is straight overhead of the barrel: a division by zero would occur because
adjacent is zero.
Because this situation occurs often in games, there is an alternative arctangent
method. Atan2 takes opposite and adjacent lengths as separate parameters, and re-
turns the equivalent in radians of 90 degrees in this situation, as desired. We use this
method to calculate the angle, as follows:
angle = ( float )Math.Atan2(opposite, adjacent);
Note that we do a cast here from double to float . This is necessary because the
Math.Atan2 method returns a value of type double , and we need to store it in a variable
of type float .The angle variable has to be of type float , because the Draw method in
the SpriteBatch class expects a float value to represent the angle. We call that method
in the Draw method of our class and we pass along the right parameters:
spriteBatch.Draw(cannonBarrel, barrelPosition, null , Color.White,
angle, barrelOrigin, 1.0f, SpriteEffects.None, 0);
5.5 What You Have Learned
In this chapter, you have learned:
how to read the current mouse position using the MouseState class and how to
change the game world using the mouse position;
Search WWH ::




Custom Search