Game Development Reference
In-Depth Information
A better FollowCamera script
If you are only targeting one device/resolution or your background scrolls indefinitely,
then the preceding manual approach works fine. However, if you want it to be a little
more dynamic, then we need to know what resolution we are working in and how much
space our character has to travel. We will perform the following steps to do this:
1. We will change the min and max variables to private as we no longer need to
configure them in the Inspector window. The code is as follows:
// The maximum x and y coordinates the camera can
have.
private Vector2 maxXAndY;
// The minimum x and y coordinates the camera can
have.
private Vector2 minXAndY;
2. To work out how much space is available in our town, we need to interrogate the
rendering size of our background sprite. So, in the Awake function, we add the
following lines of code:
// Get the bounds for the background texture -
world size
var backgroundBounds =
GameObject.Find("background").renderer.bounds;
3. In the Awake function, we work out our resolution and viewable space by inter-
rogating the ViewPort method on the camera and converting it to the same co-
ordinate type as the sprite. This is done using the following code:
// Get the viewable bounds of the camera in world
// coordinates
var camTopLeft = camera.ViewportToWorldPoint(new
Vector3(0, 0, 0));
var camBottomRight =
camera.ViewportToWorldPoint(new Vector3(1, 1, 0));
Search WWH ::




Custom Search