1)定义3个变量distance、rot、roll分别代表距离、横向角度和纵向角度(参见图2-11和图2-12)。由于Mathf.Sin和 Mathf.Cos使用弧度作为单位,因此这里的角度都用弧度来表示。根据“弧度=角度*2T /360”可以得知,30f*Mathf.PI*2/360便是30度所对应的弧度值。
2)定义变量target表示相机要跟随的物体。然后在Start()方法中通过Game-Object.Find找到场景中的坦克,赋值给target。注意Find方法的参数要与场景中的目标名相同。GameObject.Find(名字)会根据参数所指定的名字,在场景中查找物体。如果场景中存在对应名字的物体,那么它将会返回该游戏对象,否则返回null。层次面板中显示了场景中所有游戏物体的名字,读者可以右键该物体,选择Rename菜单项来修改名字(如图2-13所示)。
3)在 LateUpdate()中通过上文得出的位置关系计算出相机的新位置,最后使用transform.LookAt方法使相机对准目标。
4 ) Camera.main表示场景中的主相机,它是第一个启用的被标记为“Main-Camera”的相机。只需要给Camera.main.transform.position赋值即可设置相机位置。下列几行代码将根据2.3.1节中所叙述的数学原理,计算相机的位置,并保存到Vector3类型的cameraPos 中。
//目标的坐标
Vector3 targetPos = target.transform.position;
//用三角函数计算相机位置
Vector3 cameraPos;
float d = distance *Mathf.Cos (roll);
float height = distance * Mathf.Sin(roll);
cameraPos.x = targetPos.x +d * Mathf.Cos(rot);
cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
cameraPos.y = targetPos.y + height;
Camera.main.transform.position = cameraPos;
5 ) Camera.main.transform.LookAt()使相机旋转,对准它所跟随的物体。在调用LookAt方法后,相机的旋转角度,对准了立方体。
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
//距离
public float distance = 8;
//横向角度
public float rot = 0;
//纵向角度
private float roll = 30f * Mathf.PI * 2 / 360;
//目标物体
private GameObject target;
//横向旋转速度
public float rotSpeed = 0.2f;
//纵向角度范围
private float maxRoll = 70f * Mathf.PI * 2 / 360;
private float minRoll = -10f * Mathf.PI * 2 / 360;
//纵向旋转速度
private float rollSpeed = 0.2f;
//距离范围
public float maxDistance = 22f;
public float minDistance = 5f;
//距离变化速度
public float zoomSpeed = 0.2f;
void Start()
{
//找到坦克
//target = GameObject.Find("Tank");
SetTarget(GameObject.Find ("Tank"));
}
void LateUpdate()
{
//一些判断
if (target == null)
return;
if (Camera.main == null)
return;
//目标的坐标
Vector3 targetPos = target.transform.position;
//用三角函数计算相机位置
Vector3 cameraPos;
float d = distance *Mathf.Cos (roll);
float height = distance * Mathf.Sin(roll);
cameraPos.x = targetPos.x +d * Mathf.Cos(rot);
cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
cameraPos.y = targetPos.y + height;
Camera.main.transform.position = cameraPos;
//对准目标
Camera.main.transform.LookAt(target.transform);
//纵向旋转
Rotate();
//横向旋转
Roll();
//调整距离
Zoom();
}
//设置目标
public void SetTarget(GameObject target)
{
if (target.transform.Find("cameraPoint") != null)
this.target = target.transform.Find("cameraPoint").gameObject;
else
this.target = target;
}
//鼠标横向旋转
void Rotate()
{
float w = Input.GetAxis("Mouse X") * rotSpeed;
rot -= w;
}
//鼠标纵向旋转
void Roll()
{
float w = Input.GetAxis("Mouse Y") * rollSpeed * 0.5f;
roll -= w;
if (roll > maxRoll)
roll = maxRoll;
if (roll < minRoll)
roll = minRoll;
}
//鼠标中间的滚轮调整距离
void Zoom()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (distance > minDistance)
distance -= zoomSpeed;
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (distance < maxDistance)
distance += zoomSpeed;
}
}
}