相机一直跟随一个物体,保持相对距离移动,用鼠标滑轮可以控制相机拉近拉远,用鼠标右键控制相机做水平面圆形运动或垂直面圆形运动。
代码如下:
public class CameraFollow : MonoBehaviour//把这个脚本放到相机上
{
public Transform target;//需要跟随的目标
Vector3 offset;//相对距离
void Start()
{
offset = transform.position - target.position;
}
void Update()
{
transform.position = target.position + offset;
RotateControll();
DisControll();
}
//拉近拉远
private void DisControll()
{
float dis = offset.magnitude;
dis += Input.GetAxis("Mouse ScrollWheel") * 5;
if (dis < 10 || dis > 40)
{
return;
}
offset = offset.normalized * dis;
}
//左右上下旋转
private void RotateControll()
{
if (Input.GetMouseButton(1))
{
Vector3 pos = transform.position;
Vector3 rot = transform.eulerAngles;
//围绕target.position观察对象坐标点旋转
float movex = Input.GetAxis("Mouse X");
float movey = Input.GetAxis("Mouse Y");
float AbsX = Mathf.Abs(movex);
float AbsY = Mathf.Abs(movey);
if (AbsX > 0.05f && AbsX > AbsY)//防滑
transform.RotateAround(target.position, Vector3.up, movex * 10);
if (AbsY > 0.05f && AbsY > AbsX)//防滑
{
//这里是以y轴和相机到目标的连线组成的平面的法线为旋转轴,做出计算
Vector3 normal = Vector3.Cross(transform.position-target.position,Vector3.up);
transform.RotateAround(target.position, normal, movey * 10);
}
transform.LookAt(target);
Vector3 angle = transform.eulerAngles;
bool check = (angle.x < 85f || (angle.x > 330f ));
//控制垂直移动范围
if (!check)
{
transform.position = pos;
transform.eulerAngles = rot;
}
// 更新相对距离
offset = transform.position - target.position;
}
}
}