將腳本掛到相機上spa
private Transform player;//角色
private Transform tran;//相機
private Vector3 offsetPoint;//位置偏移
private bool isRotate = false;//是否旋轉
public float distence = 0;//相機與角色的距離
public float scrollSpeed = 10f;//拉進拉遠速度
public float rotateSpeed = 2f;//視野旋轉速度
void Start(){
tran = transform;
player = GameObject.FindGameObjectWithTag("Player").transform;
offsetPoint = transform.position - player.position;
//相機朝向角色
tran.LookAt(player.position);
}
void Update(){
//相機跟隨
tran.position = player.position + offsetPoint;
//實現視野的旋轉效果
RotateView();
//處理視野拉進拉遠的效果
ScrollView();
}
void ScrollView(){
//把向量換成長度
distence = offsetPoint.magnitude;
//距離加減獲取的鼠標中鍵的值 鼠標中鍵向前 正值(視野拉遠) 向後 負值(視野拉近)
distence += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
distence = Mathf.Clamp(distence, 2, 20);
//求新的偏移量 單位向量乘以長度
offsetPoint = offsetPoint.normalized * distence;
}
void RotateView(){
//Input.GetAxis("Mouse X") 鼠標水平方向的滑動距離
//Input.GetAxis("Mouse Y") 鼠標垂直方向的滑動距離
if (Input.GetMouseButtonDown(1)){
isRotate = true;
}
if (Input.GetMouseButtonUp(1)){
isRotate = false;
}
if (isRotate){
//以角色爲中心旋轉 水平旋轉
tran.RotateAround(player.position, player.up, Input.GetAxis("Mouse X") * rotateSpeed);
Vector3 tempPos = tran.position;
Quaternion tempRotate = tran.rotation;
//視野上下旋轉
tran.RotateAround(player.position, tran.right, -Input.GetAxis("Mouse Y") * rotateSpeed);
float x = tran.eulerAngles.x;
//限制旋轉範圍
if (x < 10 || x > 80){
//重置爲原來位置
tran.position = tempPos;
tran.rotation = tempRotate;
}
}
//更新偏移量
offsetPoint = transform.position - player.position;
}orm