Game Development Reference
In-Depth Information
To understand how does
ScreenPointToRay()
work, we have to imagine the mouse pointer as
an object in front of the camera. The resulting ray starts from the position of the camera,
passes through the position of the mouse pointer, and goes into the screen. After getting
the ray, we need a point on that ray to be the second position for the line we are going
to draw. This point must have the same distance from the camera as the projectile, which
requires us to compute the distance between the camera and the projectile first. The function
cameraRay.GetPoint()
takes a distance and returns a point on the ray that has the provided
distance from the origin of the ray, and this position is stored in
launchPosition
. The final
step is update the line by calling
line.SetPosition()
. Each time we call this function we give
it the index of the position and the point to set for that position. In the case of our line, we
have only two positions: one is the position of the projectile itself
transform.position
, and
the other is for
launchPosition
, which is the point on the ray we have computed. As a result,
the line appears between the projectile and the mouse pointer as in Illustration 66. Keep in
mind, however, that we change the actual launch position so that is has the same z value
as the projectile, which guarantees generating a force in the correct direction. Nevertheless,
drawing the line between the projectile and the actual launch position will make it appear
to the player away from the mouse pointer, which is frustrating.
Illustration 66:
Indication line drawn between the projectile and the mouse
pointer
Now we have to handle releasing the mouse button and eventually launch the projectile.
The event is handled through
OnMouseUp()
function, and it is handled only once. If the value
of
launched
is
false
, this means that the projectile has not yet been launched. Therefore, the
first thing we must do is to prevent future handling of mouse up event by setting
launched
to
true
. Before launching the projectile we have to destroy the line and invoke
Destroy()