/// <summary>
/// Created by Hong Youwei
/// Created in 2015.1
/// </summary>
using UnityEngine;
using System.Collections;
public class CameraControl : MonoBehaviour {
public float distanceAway = 3.0f; // 相机和人的水平距离
public float distanceUp = 1.0f; // 相机和人的高度差
public float smooth = 1f; // 相机移动速度
float distanceAwayR = 3.0f; // 距离调整
float distanceUpR = 1.0f; // 距离调整
private GameObject player; // 获取角色对象
private Vector3 targetPosition; // the position the camera is trying to be in
private float playerHieght; // 角色高度
private Vector3 playerPositionByHalf; // 角色的一半高
RaycastHit hit; // 获取射线信息
Vector3 curColliderPoint; // 当前遮挡物体
float distance; // 相机和人的固定距离
Transform follow; // 跟随的对象Transform
bool isFollow = true; // 是否跟随角色
void Start ()
{
// 初始化数据
distanceAwayR = distanceAway;
distanceUpR = distanceUp;
player = GameObject.FindGameObjectWithTag("Player");
playerHieght = player.collider.bounds.size.y * player.transform.localScale.y;
}
// Use this for initialization
void Update () {
}
// Update is called once per frame
void LateUpdate () {
playerPositionByHalf = new Vector3(player.transform.position.x, player.transform.position.y + playerHieght / 2, player.transform.position.z);
// 当被墙挡住时不执行这个方法
if(isFollow) {
follow = player.transform;
// setting the target position to be the correct offset from the hovercraft
targetPosition = follow.position + Vector3.up * distanceUpR - follow.forward * distanceAwayR;
// making a smooth transition between it's current position and the position it wants to be in
transform.position = Vector3.Lerp(transform.position, targetPosition, smooth * Time.deltaTime);
// make sure the camera is looking the right way!
transform.LookAt(playerPositionByHalf);
distance = Vector3.Distance(targetPosition, playerPositionByHalf);
}
// 获取是否被遮挡
Vector3 direction = (transform.position - playerPositionByHalf).normalized;
if(Physics.Raycast (playerPositionByHalf, direction, out hit, 100)) {
// 输出和碰撞体和射线
Debug.Log(hit.collider.name);
Debug.DrawLine(playerPositionByHalf, hit.point, Color.red);
Debug.DrawLine(transform.position, hit.point, Color.blue);
// CameraMesh 是在相机上设置的一个sherepher collider,用于接受来自角色身上发射出的射线检测是否被遮挡
if(hit.collider.name != "CameraMesh") {
curColliderPoint = hit.point;
}
}
// 当相机被挡住时,移到人物头顶
if (Vector3.Distance(curColliderPoint, playerPositionByHalf) < distance * 3 / 4) {
distanceAwayR = 0.5f;
distanceUpR = distanceUp * 3 / 2;
} else {
distanceAwayR = distanceAway;
distanceUpR = distanceUp;
}
}
}