using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public float distance = 18;//距离
public float rot = 0;//横向弧度
private float roll= 30f* Mathf.PI / 180;//纵向弧度,与地面成30度角的相机
private GameObject target;//目标物体
public float rotSpeed = 0.2f;
public float rollSpeed = 0.2f;
private float maxRoll = 70f * Mathf.PI / 180;
private float minRoll = 10f * Mathf.PI / 180;
public float maxDistance = 22f;
public float minDistance = 5f;
public float zoomSpeed = 0.2f;
// Use this for initialization
void Start () {
target = GameObject.Find("tank");
}
void Rotate()
{//鼠标旋转
//横向旋转
float w1 = Input.GetAxis("Mouse X") * rotSpeed;
rot -= w1;
//纵向旋转
float w2 = Input.GetAxis("Mouse Y") * rollSpeed * 0.5f;
roll -= w2;
if (roll > maxRoll)
{
roll = maxRoll;
}
else if(roll<minRoll)
{
roll = minRoll;
}
//调整距离
float w3 = Input.GetAxis("Mouse ScrollWheel");
if (w3 > 0)//向下滚动
{
if (distance > minDistance) distance -= zoomSpeed;
}
else if (w3 < 0)
{
if (distance < maxDistance) distance += zoomSpeed;
}
}
void LateUpdate () {
if (target == null)
{//找不到目标物体
return;
}
if (Camera.main == null)
{//找不到主摄像机
return;
}
Rotate();
//目标位置
Vector3 targetPos = target.transform.position;
//相机位置
Vector3 cameraPos;
float yz_d = distance * Mathf.Cos(roll);
float height = distance * Mathf.Sin(roll);
cameraPos.y = targetPos.y + height;
cameraPos.z = targetPos.z + yz_d * Mathf.Sin(rot);
cameraPos.x = targetPos.x + yz_d * Mathf.Cos(rot);
Camera.main.transform.position = cameraPos;
//对准目标
Camera.main.transform.LookAt(target.transform);
}
public void SetTarget(GameObject target)
{
if (target.transform.FindChild("cameraPoint"))
{
this.target = target.transform.FindChild("cameraPoint").gameObject;
}
else
{
this.target = target;
}
}
}
unity3d随笔-6
最新推荐文章于 2019-05-17 21:38:30 发布