using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 控制摄像机的跟随
/// </summary>
public class MaincameraController : MonoBehaviour
{
private GameObject player;
private Vector3 offsetPoistion;//角色与摄像机的位置差
private float distance;
public float ScorllSpeed;//拉近拉远的速度
public float RotateSpeed;//摄像机选择的速度
bool isRotate;//判断摄像机是否在旋转
private void Start()
{
player = GameObject.FindGameObjectWithTag(Tags.Player);
offsetPoistion = transform.position - player.transform.position;//取得角色与摄像机的位置差
}
private void Update()
{
transform.position = offsetPoistion + player.transform.position;//保持角色与摄像机的位置差,控制摄像机的移动
RotateView();
ScorllView();
}
void ScorllView()//控制摄像机的拉远拉近
{
distance = offsetPoistion.magnitude;
distance = Mathf.Clamp(distance, 2, 18);
distance -= Input.GetAxis("Mouse ScrollWheel") * ScorllSpeed;
offsetPoistion = offsetPoistion.normalized * distance;
}
void RotateView()//控制摄像机的旋转
{
if (Input.GetMouseButtonDown(0) && UICamera.isOverUI == false)
{
isRotate = true;
}
if (Input.GetMouseButtonUp(0))
{
isRotate = false;
}
if (isRotate)
{
Vector3 OriginalPos = transform.position;
Quaternion OriginalRotation = transform.rotation;
transform.RotateAround(player.transform.position, player.transform.up, RotateSpeed * Input.GetAxis("Mouse X"));
transform.RotateAround(player.transform.position, transform.right, RotateSpeed * -Input.GetAxis("Mouse Y"));
float x = transform.eulerAngles.x;
if (x < 10 || x > 80)//当旋转超出范围后把初始之传递
{
transform.position = OriginalPos;
transform.rotation = OriginalRotation;
}
}
offsetPoistion = transform.position - player.transform.position;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/db7b12a4beefc0b5fc43f380b85b0934.png)