新建一个相机作为主相机,然后将此脚本绑定到该相机,就可以实现按住鼠标右键来调整视角的效果。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour {
private const float Y_MIN = 0.0f;
private const float Y_MAX = 50.0f;
public Transform lookAt;
public Transform camTransform;
private Camera cam;
private float distance = 3.0f;
private float currentX = 0.0f;
private float currentY = 8.7f;
private float sensivityX = 4.0f;
private float sensivityY = 1.0f;
private void Start(){
camTransform = transform;
cam = Camera.main;
}
private void Update(){
if (Input.GetMouseButton (1)) {
currentX += Input.GetAxis ("Mouse X");
currentY += Input.GetAxis ("Mouse Y");
currentY = Mathf.Clamp (currentY, Y_MIN, Y_MAX);
}
if((Input.GetKey(KeyCode.A))||(Input.GetKey(KeyCode.D))||(Input.GetKey(KeyCode.W))){
//currentX = lookAt.rotation.x;
currentX += Input.GetAxis ("Horizontal")* 50.0f * Time.deltaTime*0.8f; //Auto-Adjust when your object moves or turns
}
}
private void LateUpdate(){
Vector3 dir = new Vector3 (0, 0, -distance);
Vector3 offset = new Vector3 (0,2,0); // it's optional according to your needs.
Quaternion rotation = Quaternion.Euler (currentY, currentX, 0);
camTransform.position = lookAt.position + rotation * dir;
camTransform.LookAt (lookAt.position+offset);
}
}