Game Development Reference
In-Depth Information
In the
OnTriggerEnter
function below the
if
function, add
follow.distance = 1.15f; // change the SmoothFollow distance
follow.height = 0.5f; // change the SmoothFollow height
3.
In the
OnTriggerExit
function below the
if
function, add
4.
follow.distance = 2.8f; // revert the SmoothFollow distance
follow.height = 1.8f; // revert the SmoothFollow height
5.
Save the script.
6.
Select Common Wall 2's GardenGates object, and drag the Main Camera
onto the Follow parameter.
7.
Click Play, and test the new functionality.
It's an improvement, but you would have more control if you could adjust the camera relative to how
close the gnome was to the gate. The closer the gnome is to the gateway, the closer to the gnome
the camera should be. While this solution also has some “gotchas,” it will give you a chance to try
another extremely useful bit of scripting, the
Distance()
function.
Comment out or delete the
follow
lines you added to the SensorDoors script
(including the variable declaration).
1.
2.
Save the script.
3. Create a new C# Script in the Game Scripts, and name it
DistanceDetector
.
The
Distance()
function can use
Vector2
,
Vector3
, and
Vector4
data to calculate distance.
Vector2
is
(x,y),
Vector3
is (x,y,z), and
Vector4
is (x,y,z,w). Color, a 3 or 4 part
struct
, can be (r,g,b) or (r,g,b,a). For
the gateway, the
Vector2
variety will give better results, as it can ignore the distance from the ground.
4.
Just below the class declaration, add the following variables:
public Transform targetTransform; // the gnome's transform
public Transform theCamera; // the camera's transform
Vector2 source; // the gateway
Vector2 target; // the gnome
Using a
Vector2
means you will have to assign the x and z values from the transform manually.
In the
Start
function, add the following:
5.
// assign the x and z position to the source var
source = new Vector2(transform.position.x,transform.position.z);
A
Struct
, or structure, is a value type that is typically used to encapsulate small groups of related
variables. To access the elements of the struct, one uses dot notation.
The target, the Gnomatic Garden Defender, because it may be moving, must be updated every
frame. To begin with, you will have the distance printed out in the console.