Game Development Reference
In-Depth Information
Inside the GameWorld class, we store a member variable of the type Ball :
Ball ball;
And in the GameWorld constructor method, we create an instance of the Ball class:
ball = new Ball(Content);
8.2.3 Shooting the Ball
The player can click the left mouse button in the game screen to shoot a ball of
paint. The speed of the ball and the direction in which it is moving is determined
by the position where the player clicks. The ball should move in the direction of
that position, and the further away a player clicks from the cannon, the higher the
speed of the ball will be. In order to handle input, we add a HandleInput method to
the Ball class. Inside this method, we can check whether the player clicks with the
left button by using the input helper:
if (inputHelper.MouseLeftButtonPressed())
dosomething...
However, since there can only be a single ball in the air at any moment, we only
want to do something if the ball is not already in the air. This means that we have to
check what the shooting status of the ball is. If the ball is already shooting, we do
not have to handle the mouse click. So, we extend our if -instruction with an extra
condition that the ball currently is not shooting as follows:
if (inputHelper.MouseLeftButtonPressed() && !shooting)
dosomething...
As you can see, we are using several logical operators ( && and ! ) in conjunction here.
Because of the logical 'not' ( ! ) operator, the entire condition in the if -instruction
will only evaluate to true if the shooting variable has the value false , or: the ball is
currently not shooting.
Inside the if -instruction, we need to do a couple of things. We know that the
player has clicked somewhere and that the ball has to be shot from the cannon. The
first thing that we need to do is set the variable shooting to the correct value, because
the status of the ball will need to be changed to 'currently shooting':
shooting = true ;
In the Reset method, we have already given the ball an initial position. What we now
need to do is give the ball a velocity . This velocity will be a vector in the direction of
the place where the player has clicked. We can calculate this direction by subtracting
the ball position from the mouse position. For this, we will use the handy property
 
Search WWH ::




Custom Search