Game Development Reference
In-Depth Information
}
Tip
An alternative to discovering the player this way is to make the player property public
and then assign it in the editor. There is no right or wrong way—just your preference.
It is also a good practice to add some element of debugging to let you know if there is a
problem in the scene with a missing reference, else all you will see are errors such as ob-
ject not initialized or variable was null.
Next, we need a couple of helper methods to check whether the player has moved near the
edge of the camera's bounds as defined by the Max X and Y variables. In the following
code, we will use the settings defined in the preceding code to control how close you can
get to the end result:
bool CheckXMargin()
{
// Returns true if the distance between the camera
and the
// player in the x axis is greater than the x margin.
return Mathf.Abs
(transform.position.x - player.position.x) > xMargin;
}
bool CheckYMargin()
{
// Returns true if the distance between the camera
and the
// player in the y axis is greater than the y margin.
return Mathf.Abs
(transform.position.y - player.position.y) > yMargin;
}
To finish this script, we need to check each frame when the scene is drawn to see whether
the player is close to the edge and update the camera's position accordingly. Also, we need
to check if the camera bounds have reached the edge of the screen and not move it bey-
ond.
Search WWH ::




Custom Search