using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollowss : MonoBehaviour {
? ? //跟隨目標(biāo)
? ? //先確定相機圍繞哪個物體進(jìn)行旋轉(zhuǎn),縮放,平移;也就是需要確定相機的父物體
? //先寫右鍵旋轉(zhuǎn)(相機),確定相機旋轉(zhuǎn)的速度
? public Transform target;
? //旋轉(zhuǎn)的初始角度
? private float x = 0.0f;
? ? private float y = 0.0f;
? //相機旋轉(zhuǎn)的速率
? private float rSpeed = 10.0f;
? //獲取相機Transform對象
? private Transform cam;
? //相機距離目標(biāo)物體的起始距離(距離設(shè)置為負(fù)值,是因為相機是在目標(biāo)物體的正后方)
? private float distance = -5;
? //相機距離的物體的最近和最遠(yuǎn)距離
? private float minDistance = -1;
? ? private float maxDistance = -30;
? //初始位置
? private float camPostion_x = 0;
? ? private float camPostion_y = 0;
? ? void Awake()
? ? {
? ? ? ? transform.position = target.position;
? ? ? ? transform.rotation = Quaternion.Euler(y, x, 0);
? ? ? ? cam = GameObject.Find("Main Camera").transform;
? ? ? ? cam.localPosition = new Vector3(0, 0, distance);
? ? }
? ? void Update()
? ? {
? ? ? ? if (Input.GetMouseButton(1))
? ? ? ? {
? ? ? //右鍵按下
? ? ? x += Input.GetAxis("Mouse X") * rSpeed;
? ? ? ? ? ? y -= Input.GetAxis("Mouse Y") * rSpeed;
? ? ? ? ? ? x = ClampAngle(x, -360, 360);
? ? ? ? ? ? y = ClampAngle(y, -70, 70);
? ? ? ? ? ? var rotation = Quaternion.Euler(y, x, 0);
? ? ? ? ? ? transform.rotation = rotation;
? ? ? ? }
? ? ? ? else if (Input.GetAxis("Mouse ScrollWheel") != 0)
? ? ? ? {
? ? ? //中鍵滾動縮放
? ? ? distance += Input.GetAxis("Mouse ScrollWheel") * 5;
? ? ? ? ? ? distance = Mathf.Clamp(distance, maxDistance, minDistance);
? ? ? ? ? ? cam.localPosition = new Vector3(camPostion_x, camPostion_y, distance);
? ? ? ? }
? ? //中鍵按下平移
? ? if (Input.GetMouseButton(2))
? ? ? ? {
? ? ? ? ? ? camPostion_x -= Input.GetAxis("Mouse X") * 0.04f;
? ? ? ? ? ? camPostion_y -= Input.GetAxis("Mouse Y") * 0.04f;
? ? ? ? ? ? cam.localPosition = new Vector3(camPostion_x, camPostion_y, distance);
? ? ? ? }
? ? }
? ? static float ClampAngle(float angle, float minAngle, float maxAngle)
? ? {
? ? ? ? if (angle < -360)
? ? ? ? ? ? angle += 360;
? ? ? ? if (angle > 360)
? ? ? ? ? ? angle -= 360;
? ? ? ? return Mathf.Clamp(angle, minAngle, maxAngle);
? ? }
}